<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/8/2
 * Time: 13:20
 */

namespace app\api\model;


use constant\config;
use phpDocumentor\Reflection\Types\Object_;
use think\Db;
use think\Model;
use think\Request;

class OrderModel extends Model {
    protected $table = 'order';
    
    /*
     * 算余额
     */
    public static function offer($order_id, $type = 2) {
        $list                             = [];
        $list['yu']                       = 0;
        $thro                             = db('envelopes')->where(['ordesr_id' => $order_id, 'type' => 1])->find();
        $cap                              = db('capital')->where(['envelopes_id' => $thro['envelopes_id'], 'types' => 1, 'enable' => 1])->field('to_price,capital_id,agency')->select();
        $to_price                         = array_sum(array_column($cap, 'to_price'));
        $capital_id                       = array_column($cap, 'capital_id');
        $auxiliary_delivery_scheduleCount = db('auxiliary_delivery_schedule')->Join('auxiliary_project_list', 'auxiliary_delivery_schedule.auxiliary_project_list_id=auxiliary_project_list.id', 'left')->whereIn('auxiliary_project_list.capital_id', $capital_id)->whereNull('auxiliary_project_list.delete_time')->whereNull('auxiliary_delivery_schedule.delete_time')->count();
        $auxiliaryNodeId                  = db('auxiliary_delivery_node')->Join('auxiliary_delivery_schedule', 'auxiliary_delivery_schedule.id=auxiliary_delivery_node.auxiliary_delivery_schedul_id', 'left')->Join('auxiliary_project_list', 'auxiliary_delivery_schedule.auxiliary_project_list_id=auxiliary_project_list.id', 'left')->whereIn('auxiliary_project_list.capital_id', $capital_id)->whereNull('auxiliary_project_list.delete_time')->whereNull('auxiliary_delivery_schedule.delete_time')->field('auxiliary_delivery_node.state,auxiliary_delivery_node.auxiliary_delivery_schedul_id')->select();
        $list['auxiliaryState']           = 0;
        $auxiliaryCount                   = array_column($auxiliaryNodeId, 'auxiliary_delivery_schedul_id');
        
        if ($auxiliary_delivery_scheduleCount > count(array_merge(array_unique($auxiliaryCount)))) {
            $list['auxiliaryState'] = 1;
        }
        $auxiliaryId = array_column($auxiliaryNodeId, 'state');
        
        if ($auxiliaryId) {
            if (in_array(0, $auxiliaryId)) {
                $list['auxiliaryState'] = 2;
            }
        }
        $list['yc']     = empty($thro['through_id']) ? 0 : 1;
        $list['amount'] = $to_price - $thro['give_money'] + $thro['expense'];
        $list['agency'] = 0;
        $list['man']    = 0;
        
        $list['mainContract'] = 0;
        $manArray             = [];
        $agencyArray          = [];
        foreach ($cap as $item) {
            if ($item['agency'] == 1) {
                $list['agency'] = 1;
                $agencyArray[]  = $item['to_price'];
            }
            
            if ($item['agency'] == 0) {
                $list['mainContract'] = 1;
                $manArray[]           = $item['to_price'];
            }
            
        }
        $agency = array_sum($agencyArray);
        if (!empty($agency)) {
             $list['agency'] = bcadd($agency , $thro['purchasing_expense'],2) - $thro['purchasing_discount'];
        }
        if (!empty($manArray)) {
            $list['man'] = bcsub(array_sum($manArray) , $thro['give_money'],2) + $thro['expense'];
        }
        if (!empty($list['amount']) && !empty($agency)) {
            $list['amount'] = bcadd($list['amount'] ,$thro['purchasing_expense'],2) - $thro['purchasing_discount'];
        }
        $list['auditedAmount'] = 0;
        $list['yu']            = $list['amount'];
        $list['gong']          = $thro['gong'];
        
        if ($list['yu'] > 0) {
            
            $Common                = \app\api\model\Common::order_for_payment($order_id);
            $list['yu']            = sprintf('%.2f', $list['amount'] - $Common[0] - $Common[1]);
            $list['auditedAmount'] = $Common[2];
            $list['rejectMoney']   = $Common[3];
            sprintf('%.2f', $list['yu']);
        } else {
            $list['rejectMoney'] = "0";
        }
        
        return $list;
    }
    
    //新版算余额
    public function newOffer($order_id) {
        
        $cap = db('capital')->where(['ordesr_id' => $order_id, 'types' => 1, 'enable' => 1])->field('sum(to_price) as to_price,envelopes_id')->select();
        if (!empty($cap[0]['to_price'])) {
            $ca             = db('envelopes')->where(['envelopes_id' => $cap[0]['envelopes_id']])->field('give_money,expense,purchasing_expense,purchasing_discount')->find();
            $list['amount'] = $cap[0]['to_price'] - $ca['give_money'] + $ca['expense'] + $ca['purchasing_expense'] - $ca['purchasing_discount'];
        } else {
            $list['amount'] = 0;
        }
        
        return $list;
    }
    
    /*
     * 主材代购分开算
     */
    public function TotalProfit($order_id) {
        $manZhiShou=0;
         $daiZhiShou=0;
        $cap = db('capital')->where(['types' => 1, 'enable' => 1])->whereIn('ordesr_id', $order_id)->field('capital_id,agency,envelopes_id,to_price,settlement_method,give,sub_expense_money')->select();
        if (!empty($cap)) {
            $agency       = [];
            $MainMaterial = [];
            foreach ($cap as $item) {
                if ($item['agency'] == 1) {
                    $agency[] = $item;
                     if (($item['settlement_method'] == 3 || $item['settlement_method'] == 4)) {
                         if($item['give'] !=0){
                            $item['to_price']=0;
                        }
                        $daiZhiShou +=bcadd($item['to_price'],$item['sub_expense_money'],2);
                      }
                }
                if ($item['agency'] == 0) {
                    $MainMaterial[] = $item;
                     if (($item['settlement_method'] == 3 || $item['settlement_method'] == 4)) {
                        if($item['give'] !=0){
                            $item['to_price']=0;
                        }
                        $manZhiShou +=bcadd($item['to_price'],$item['sub_expense_money'],2);
                    }
                }
            }
            $list['MainMaterialCapitalId'] = array_column($MainMaterial, 'capital_id');
            $MainMateriaEnvelopes_id       = array_unique(array_column($MainMaterial, 'envelopes_id'));
            $agencyEnvelopes_id            = array_unique(array_column($agency, 'envelopes_id'));
            $Envelopes_id                  = array_merge($agencyEnvelopes_id, $MainMateriaEnvelopes_id);
            $ca                            = db('envelopes')->whereIn('envelopes_id', $Envelopes_id)->field('(sum(give_money)-sum(expense)) as zhuMoney,sum(give_money) as zhuGiveMoney,sum(expense) as zhuExpense, (sum(purchasing_discount)-sum(purchasing_expense)) as daiMoney,sum(purchasing_discount) AS daiGiveMoney,(purchasing_expense) AS daiExpense')->select();
            $list['agencyMoney']           = sprintf('%.2f', array_sum(array_column($agency, 'to_price')) - $ca[0]['daiMoney']);
            $list['MainMaterialMoney']     = sprintf('%.2f', array_sum(array_column($MainMaterial, 'to_price')) - $ca[0]['zhuMoney']);
            $list['capital_main_total']    = sprintf('%.2f', array_sum(array_column($MainMaterial, 'to_price')));
            $list['capital_agent_total']   = sprintf('%.2f', array_sum(array_column($agency, 'to_price')));
            $list['main_give_money']       = sprintf('%.2f', $ca[0]['zhuGiveMoney']);
            $list['agent_give_money']      = sprintf('%.2f', $ca[0]['daiGiveMoney']);
            $list['main_expense']          = sprintf('%.2f', $ca[0]['zhuExpense']);
            $list['agent_expense']         = sprintf('%.2f', $ca[0]['daiExpense']);
            $list['manZhiShou']          = $manZhiShou;
            $list['daiZhiShou']         = $daiZhiShou;
        } else {
            $list['agencyMoney']           = 0;
            $list['MainMaterialMoney']     = 0;
            $list['MainMaterialCapitalId'] = 0;
            $list['capital_main_total']    = 0;
            $list['capital_agent_total']   = 0;
            $list['main_give_money']       = 0;
            $list['agent_give_money']      = 0;
            $list['main_expense']          = 0;
            $list['agent_expense']         = 0;
             $list['manZhiShou']          = 0;
            $list['daiZhiShou']         = 0;
            
        }
        
        return $list;
    }
    
    /*
    * 结算用算款项
    */
    public function SingleSettlement($order_id) {
        
        $cap = db('capital')->where(['types' => 1, 'enable' => 1])->where('ordesr_id', $order_id)->field('capital_id,agency,envelopes_id,to_price,sub_discounted_money,over_limit_discount,products_sub_discounted_money,settlement_method,fixed_rate,class_b,sub_expense_money,fixed_cost,give')->select();
         // 常规的就是之前的算法，
         $manConvention=[];
         $agenConvention=[];
         // 公司固定计提：（清单的金额-sub_discounted_money-products_sub_discounted_money）*比例；settlement_method = 2
         $manFixedCompany=[];
         $agenFixedCompany=[];
         // 直售固提清单：（清单的金额-sub_discounted_money-products_sub_discounted_money-签约之后的超限优惠）*比例；  settlement_method = 3 || 4
         $manDirectSalesAndFixedDeliver=[];
         $agenDirectSalesAndFixedDeliver=[];
        if (!empty($cap)) {
            $agency       = [];
            $MainMaterial = [];
            foreach ($cap as $item) {
                if ($item['agency'] == 1) {
                    $agency[] = $item;
                    if ($item['settlement_method'] == 1) {
                        if($item['give'] !=0){
                            $item['to_price']=0;
                        }
                         //清单金额
                        $agenConvention[]=bcadd(bcsub(bcadd(bcsub( $item['to_price'],$item['sub_discounted_money'],2),$item['sub_expense_money'],2),$item['products_sub_discounted_money'],2),$item['over_limit_discount'],2);
                    }
                    if ($item['settlement_method'] == 2) {
                         // //清单金额
                         if($item['give'] !=0){
                            $item['to_price']=0;
                        }
                        $originally_to_price=bcadd(bcsub(bcadd(bcsub( $item['to_price'],$item['sub_discounted_money'],2),$item['sub_expense_money'],2),$item['products_sub_discounted_money'],2),$item['over_limit_discount'],2);
                        $to_price=bcmul($originally_to_price,bcdiv($item['fixed_rate'],100,2),2);
                        $agenFixedCompany[]= ['to_price'=>$to_price,'title'=>$item['class_b']."（".$item['fixed_rate']."%）". $to_price."元",'originally_to_price'=>$originally_to_price];
                    }
                    if (($item['settlement_method'] == 3 || $item['settlement_method'] == 4)) {
                         //清单金额
                         $originally_to_price_give=bcadd($item['to_price'],$item['sub_expense_money'],2);
                        if($item['give'] !=0){
                            $item['to_price']=0;
                        }
                        //清单金额
                        $originally_to_price=bcadd($item['to_price'],$item['sub_expense_money'],2);
                        
                        //直售提成
                        $to_price=bcmul($originally_to_price,bcdiv($item['fixed_rate'],100,2),2);
                        //直售固定成本
                        $fixed_cost= bcmul($originally_to_price_give,bcdiv($item['fixed_cost'],100,2),2);
                        
                        $agenDirectSalesAndFixedDeliver[]=['to_price'=> $to_price,'title'=>$item['class_b']."（".$item['fixed_rate']."%）". $to_price."元",'originally_to_price'=>$originally_to_price,'fixed_cost'=>$fixed_cost];
                    }
                }
                if ($item['agency'] == 0) {
                    $MainMaterial[] = $item;
                    if ($item['settlement_method'] == 1) {
                        if($item['give'] !=0){
                            $item['to_price']=0;
                        }
                        $manConvention[]=bcadd(bcsub(bcadd(bcsub( $item['to_price'],$item['sub_discounted_money'],2),$item['sub_expense_money'],2),$item['products_sub_discounted_money'],2),$item['over_limit_discount'],2);
                    
                    }
                    if ($item['settlement_method'] == 2) {
                        if($item['give'] !=0){
                            $item['to_price']=0;
                        }
                        //清单金额
                        $originally_to_price=bcadd(bcsub(bcadd(bcsub( $item['to_price'],$item['sub_discounted_money'],2),$item['sub_expense_money'],2),$item['products_sub_discounted_money'],2),$item['over_limit_discount'],2);
                         //公司固定计提
                         $to_price=bcmul($originally_to_price,bcdiv($item['fixed_rate'],100,2),2);
                       
                        $manFixedCompany[]= ['to_price'=>$to_price,'title'=>$item['class_b']."（".$item['fixed_rate']."%）". $to_price."元",'originally_to_price'=>$originally_to_price];
                    }
                    if (($item['settlement_method'] == 3 || $item['settlement_method'] == 4)) {
                         //清单金额
                         $originally_to_price_give=bcadd($item['to_price'],$item['sub_expense_money'],2);
                     
                        if($item['give'] !=0){
                            $item['to_price']=0;
                        }
                        //清单金额
                        $originally_to_price=bcadd($item['to_price'],$item['sub_expense_money'],2);
                        //直售提成
                        $to_price=bcmul($originally_to_price,bcdiv($item['fixed_rate'],100,2),2);
                        //直售固定成本
                        $fixed_cost= bcmul($originally_to_price_give,bcdiv($item['fixed_cost'],100,2),2);
                        
                        $manDirectSalesAndFixedDeliver[]=['to_price'=> $to_price,'title'=>$item['class_b']."（".$item['fixed_rate']."%）". $to_price."元",'originally_to_price'=>$originally_to_price,'fixed_cost'=>$fixed_cost];
                    }
                }
                
            }
            $Envelopes_id              = $cap[0]['envelopes_id'];
            $ca                        = db('envelopes')->where('envelopes_id', $Envelopes_id)->find();
            $list['agencyMoney']       = sprintf('%.2f', array_sum(array_column($agency, 'to_price')) + $ca['purchasing_expense'] - $ca['purchasing_discount']);
            $list['MainMaterialMoney'] = sprintf('%.2f', array_sum(array_column($MainMaterial, 'to_price')) - $ca['give_money'] + $ca['expense']);
            $list['manConvention']           = $manConvention;
            $list['manFixedCompany']           = $manFixedCompany;
            $list['manDirectSalesAndFixedDeliver']           = $manDirectSalesAndFixedDeliver;
            $list['agenConvention']           = $agenConvention;
            $list['agenFixedCompany']           = $agenFixedCompany;
            $list['agenDirectSalesAndFixedDeliver']           = $agenDirectSalesAndFixedDeliver;
        } else {
            $list['agencyMoney']           = 0;
            $list['agenConvention']           = $agenConvention;
            $list['agenFixedCompany']           = $agenFixedCompany;
            $list['agenDirectSalesAndFixedDeliver']           = $agenDirectSalesAndFixedDeliver;
            $list['manConvention']           = $manConvention;
            $list['manFixedCompany']           = $manFixedCompany;
            $list['manDirectSalesAndFixedDeliver']           = $manDirectSalesAndFixedDeliver;
            $list['MainMaterialMoney']     = 0;
            $list['MainMaterialCapitalId'] = 0;
            
        }
        
        return $list;
    }
    
    //推客只算主合同s
    public function TuiNewOffer($order_id) {
        
        $content = 0;
        if (substr($order_id, 0, 3) != config('city')) {
            $content = $this->UrbanAccess(substr($order_id, 0, 3));
        }
        
        if ($content == 0) {
            $capital   = db('capital');
            $envelopes = db('envelopes');
        } else {
            $capital   = Db::connect($content)->table('capital');
            $envelopes = Db::connect($content)->table('envelopes');
        }
        $cap = $capital->where(['ordesr_id' => $order_id, 'types' => 1, 'enable' => 1, 'agency' => 0])->field('sum(to_price) as to_price,envelopes_id')->select();
        if (!empty($cap[0]['to_price'])) {
            $ca             = $envelopes->where(['envelopes_id' => $cap[0]['envelopes_id']])->field('give_money,expense,purchasing_expense,purchasing_discount')->find();
            $list['amount'] = $cap[0]['to_price'] - $ca['give_money'] + $ca['expense'];
        } else {
            $list['amount'] = 0;
        }
        
        return $list;
    }
    
    public function ccSchemeLabel() {
        return $this->hasMany('cc_scheme_label', 'order_id');
    }
    
    /*
     * 批量更新清零
     */
    public function MultiTableUpdate($orderId, $type) {
        // $list = \db('order')
        //     ->Join('envelopes', 'envelopes.ordesr_id=order.order_id', 'left')
        //     ->Join('through', 'through.order_ids=order.order_id', 'left')
        //     ->Join('warranty_collection', 'warranty_collection.order_id=order.order_id', 'left')
        //     ->Join('capital', 'capital.ordesr_id=order.order_id', 'left')
        //     ->where('order.order_id', $orderId)
        //     ->update(['envelopes.type' => $type, 'capital.enable' => $type, 'through.baocun' => $type, 'warranty_collection.type' => $type]);
        // return $list;
        \db('envelopes')->where('ordesr_id', $orderId)->update(['type' => 0]);
        \db('warranty_collection')->where('order_id', $orderId)->update(['type' => 0]);
        \db('capital')->where('ordesr_id', $orderId)->update(['enable' => 0]);
    }
    
    /*
     * 更新order主材
     */
    public function orderAgency($data) {
        $this->isUpdate(true)->save($data);
    }
    
    public function order_list($count, $_begin, $_end, $user_id, $store_id) {
        $condition = [];
        switch ($count) {
            //自己成交
            case 1:
                $condition['order.assignor'] = $user_id;
                break;
            //店铺成交
            default :
                $user                  = db('user')->where('store_id', $store_id)->column('user_id');
                $condition['assignor'] = ['in', $user];
                break;
            
        }
        $g1 = db('contract')->where(['con_time' => ['between', [$_begin, $_end]], 'type' => 1])->column('orders_id');
        
        //全部订单
        $order = OrderModel::where($condition)->whereIn('order_id', $g1)->where('state', '<', 8)->field('order_id,ification')//                ->fetchSql(true)
        ->select();
        
        //        var_dump($order);die;
        return $order;
        
    }
    
    /*
     *  人工成本计算
     */
    public function ManualSettlement1($order_id) {
        $ca      = db('envelopes')->where(['ordesr_id' => $order_id])->where('type', 1)->field('give_money,project_title,envelopes_id,gong')->find();
        $capital = db('capital')->join('detailed','detailed.detailed_id=capital.projectId','left')->join('detailed_category', 'detailed_category.id=detailed.detailed_category_id', 'left')->join('unit un', 'un.id=detailed.un_id', 'left')->field('detailed.*,un.title,detailed_category.title as titles,detailed_category.id,capital.*')->where(['capital.ordesr_id' => $order_id, 'capital.types' => 1, 'capital.enable' => 1, 'capital.agency' => 0])->where('envelopes_id', $ca['envelopes_id'])->select();
        $pr      = null;
        foreach ($capital as $k => $item) {
            if ($item['fen'] == 1) {
                $detailed = db('detailed')->where(['detailed_id' => $item['projectId']])->join('detailed_category', 'detailed_category.id=detailed.detailed_category_id', 'left')->join('unit un', 'un.id=detailed.un_id', 'left')->field('detailed.*,un.title,detailed_category.title as titles,detailed_category.id')->find();
                
                $cleared_time = db('order')->where(['order_id' => $order_id])->value('cleared_time');
                if ($item['labor_cost'] == 0.000 && $item['revised'] == 0 && empty($cleared_time)) {
                    
                    if ($detailed['insufficient'] > $item['square']) {
                        
                        $capital[$k]['pri'] = $detailed['insufficient'] * $detailed['pri'];
                        
                    } elseif ($detailed['insufficient'] < $item['square'] && $detailed['exceed'] == 0) {
                        
                        $capital[$k]['pri'] = $item['square'] * $detailed['pri'];
                        
                    } elseif ($detailed['insufficient'] == $item['square']) {
                        
                        $capital[$k]['pri'] = $item['square'] * $detailed['pri'];
                        
                    } elseif ($detailed['exceed'] == $item['square']) {
                        
                        $capital[$k]['pri'] = $item['square'] * $detailed['pri'];
                        
                    } elseif ($detailed['insufficient'] < $item['square'] && $detailed['insufficient'] != 0) {
                        
                        if ($item['square'] < $detailed['exceed'] && $detailed['exceed'] != 0) {
                            
                            $capital[$k]['pri'] = $item['square'] * $detailed['pri'];
                        } elseif ($item['square'] > $detailed['exceed'] && $detailed['exceed'] != 0 && $detailed['pri1'] != 0.00 && $detailed['exceed1'] == 0) {
                            
                            $capital[$k]['pri'] = $item['square'] * $detailed['pri1'];
                        } elseif ($item['square'] > $detailed['exceed'] && $detailed['exceed'] != 0 && $detailed['pri1'] != 0.00 && $detailed['exceed1'] != 0 && $item['square'] < $detailed['exceed1']) {
                            
                            $capital[$k]['pri'] = $item['square'] * $detailed['pri1'];
                        } elseif ($item['square'] < $detailed['exceed'] && $detailed['exceed'] != 0 && $detailed['pri1'] == 0.00) {
                            
                            $capital[$k]['pri'] = $item['square'] * $detailed['pri'];
                        } elseif ($detailed['exceed'] != 0 && $item['square'] > $detailed['exceed1']) {
                            
                            $capital[$k]['pri'] = $item['square'] * $detailed['pri2'];
                        } elseif ($detailed['exceed'] == $item['square']) {
                            
                            $capital[$k]['pri'] = $item['square'] * $detailed['pri'];
                        } elseif ($detailed['exceed1'] == $item['square']) {
                            
                            $capital[$k]['pri'] = $item['square'] * $detailed['pri1'];
                        } elseif ($item['square'] > $detailed['exceed'] && $detailed['exceed1'] != 0 && $detailed['pri2'] == 0.00 && $detailed['exceed'] != 0) {
                            $capital[$k]['pri'] = $item['square'] * $detailed['pri2'];
                        }
                        
                        
                    } elseif ($detailed['insufficient'] == 0 && $detailed['exceed'] != 0 && $item['square'] > $detailed['exceed']) {
                        $capital[$k]['pri'] = $item['square'] * $detailed['pri1'];
                    } elseif ($detailed['insufficient'] == 0 && $detailed['exceed'] != 0 && $item['square'] == $detailed['exceed']) {
                        
                        $capital[$k]['pri'] = $item['square'] * $detailed['pri'];
                    } elseif ($detailed['insufficient'] == 0 && $detailed['exceed'] != 0 && $item['square'] < $detailed['exceed']) {
                        
                        $capital[$k]['pri'] = $item['square'] * $detailed['pri'];
                    } elseif ($detailed['insufficient'] == 0 && $detailed['exceed'] == 0 && $detailed['exceed1'] == 0) {
                        
                        $capital[$k]['pri'] = $detailed['pri'];
                    }
                    
                    $pr[$k]['projectId']    = $item['capital_id'];
                    $pr[$k]['projectMoney'] = empty($detailed['artificial']) ? 0 : $detailed['artificial'];
                    $pr[$k]['projectTitle'] = $detailed['detailed_title'];
                    $pr[$k]['title']        = $detailed['title'];
                    $pr[$k]['pris']         = $detailed['pris'];
                    $pr[$k]['zhi']          = $item['zhi'];
                    $pr[$k]['square']       = $item['square'];
                    $pr[$k]['cooperation']  = $item['cooperation'];
                    $pr[$k]['material']     = $detailed['material'];
                    $pr[$k]['to_price']     = empty($item['to_price']) ? 0 : $item['to_price'];
                    $pr[$k]['pri']          = sprintf('%.2f', $capital[$k]['pri']);
                    $pr[$k]['titles']       = $detailed['titles'];
                    $pr[$k]['id']           = $detailed['id'];
                    
                } else {
                    $pr[$k]['projectId']    = $item['capital_id'];
                    $pr[$k]['projectMoney'] = empty($detailed['artificial']) ? 0 : $detailed['artificial'];
                    $pr[$k]['projectTitle'] = $detailed['detailed_title'];
                    $pr[$k]['title']        = $detailed['title'];
                    $pr[$k]['pris']         = $detailed['pris'];
                    $pr[$k]['zhi']          = $item['zhi'];
                    $pr[$k]['square']       = $item['square'];
                    $pr[$k]['pri']          = $item['labor_cost'];
                    $pr[$k]['material']     = $item['material'];
                    $pr[$k]['cooperation']  = $item['cooperation'];
                    $pr[$k]['to_price']     = empty($item['to_price']) ? 0 : $item['to_price'];
                    $pr[$k]['titles']       = $detailed['titles'];
                    $pr[$k]['id']           = $detailed['id'];
                }
                
            } elseif ($item['fen'] == 0) {
                $product_chan = db('product_chan')->join('unit u', 'product_chan.units_id=u.id', 'left')->where(['product_id' => $item['projectId']])->field('product_chan.product_title,product_chan.prices,u.title,product_chan.materials')->find();
                
                $pr[$k]['projectId']    = $item['capital_id'];
                $pr[$k]['projectMoney'] = $product_chan['prices'];
                $pr[$k]['projectTitle'] = $product_chan['product_title'];
                $pr[$k]['title']        = $product_chan['title'];
                $pr[$k]['square']       = $item['square'];
                $pr[$k]['pris']         = $product_chan['materials'];
                $pr[$k]['zhi']          = $item['zhi'];
                $pr[$k]['pri']          = $item['labor_cost'];
                $pr[$k]['material']     = $item['material'];
                $pr[$k]['to_price']     = empty($item['to_price']) ? 0 : $item['to_price'];
                $pr[$k]['cooperation']  = $item['cooperation'];
                $pr[$k]['titles']       = '';
                $pr[$k]['id']           = 0;
            } elseif ($item['fen'] == 2) {
                $pr[$k]['projectId']    = $item['capital_id'];
                $pr[$k]['projectMoney'] = $item['un_Price'];
                $pr[$k]['projectTitle'] = $item['class_b'];
                $pr[$k]['pris']         = '';
                $pr[$k]['zhi']          = $item['zhi'];
                $pr[$k]['square']       = $item['square'];
                $pr[$k]['title']        = $item['company'];
                $pr[$k]['to_price']     = empty($item['to_price']) ? 0 : $item['to_price'];
                $pr[$k]['pri']          = $item['labor_cost'];
                $pr[$k]['material']     = $item['material'];
                $pr[$k]['cooperation']  = $item['cooperation'];
                $pr[$k]['titles']       = '';
                $pr[$k]['id']           = 0;
            } elseif ($item['fen'] == 4) {
                // $detailed = db('detailed')->where(['detailed_id' => $item['projectId']])->join('detailed_category', 'detailed_category.id=detailed.detailed_category_id', 'left')->join('unit un', 'un.id=detailed.un_id', 'left')->field('detailed.*,un.title,detailed_category.title as titles,detailed_category.id')->find();
                
                $pr[$k]['projectId']    = $item['capital_id'];
                $pr[$k]['projectMoney'] = $item['un_Price'];
                $pr[$k]['projectTitle'] = $item['class_b'];
                $pr[$k]['pris']         = '';
                $pr[$k]['zhi']          = $item['zhi'];
                $pr[$k]['square']       = $item['square'];
                $pr[$k]['title']        = $item['company'];
                $pr[$k]['pri']          = $item['labor_cost'];
                $pr[$k]['material']     = $item['material'];
                $pr[$k]['cooperation']  = $item['cooperation'];
                $pr[$k]['to_price']     = empty($item['to_price']) ? 0 : $item['to_price'];
                $pr[$k]['titles']       = $item['titles'];
                $pr[$k]['id']           = $item['id'];
                
            }
            $pr[$k]['categoryName1'] = $item['categoryName'];
            $approval_record       = \db('approval_record', config('database.zong'))->where('relation_id', $item['capital_id'])->where('type', 6)->where('city_id', config('cityId'))->where('status', 0)->order('id desc')->find();
            $pr[$k]['auditStatus'] = '';
            if (!empty($approval_record['change_value'])) {
                $pr[$k]['auditStatus'] = '工费超限申请中，申请金额: ' . $approval_record['change_value'] . '元';
            }
           
            //原始工费
            $pr[$k]['oldLaborCost'] = $item['square'] * $item['labor_cost_price'];
            //店长下调工费
            $downregulation = 0;
            $upRegulation   = 0;
            if ($pr[$k]['oldLaborCost'] - $pr[$k]['pri'] > 0) {
                $downregulation = bcsub($pr[$k]['oldLaborCost'], $pr[$k]['pri']);
            }
            if ($pr[$k]['oldLaborCost'] - $pr[$k]['pri'] < 0) {
                $upRegulation = bcsub(bcadd($pr[$k]['pri'], $approval_record['change_value'], 2), $pr[$k]['oldLaborCost'], 2);
            }
            $pr[$k]['downregulation'] = $downregulation;
            //店长上调工费
            $pr[$k]['upRegulation'] = $upRegulation;
            //报销使用工费
            // $o                                = new  Common();
            // $moneyQian                        = $o->availableReimbursementLimit($order_id, $item['capital_id']);
            $moneyQian=0;
            $isEdit=0;
            // $capital_minus_beforehand=db('capital_minus_beforehand')->where('capital_id', $pr[$k]['projectId'])->where('delete_time', 0)->where('types', 1)->select();
            // $dangCapital_minus_beforehand=db('capital_minus_beforehand')->where('minus_id', $pr[$k]['projectId'])->where('delete_time', 0)->where('types', 1)->select();
            $pr[$k]['laborCostReimbursement'] = $item['labor_cost_reimbursement'] + $moneyQian;
            // if (!empty($capital_minus_beforehand) || !empty($dangCapital_minus_beforehand)) {
            //     $isEdit=1;
            // }
           
            $approval  = Db::connect(config('database.zong'))->table('approval')->where('relation_id', $pr[$k]['projectId'])->where('status', 0)->where('type', 8)->select();
            if(!empty($approval)){
                $isEdit=1;
            }
            $pr[$k]['isEdit'] = $isEdit;
            $pr[$k]['requestedAmount']        = $item['requested_amount'];
            if ($item['requested_amount'] == 0) {
                $pr[$k]['requestedAmount'] = $item['square'] * $item['labor_cost_price'];
            }
            $list              = \db('auxiliary_project_list')->Join('order_setting', 'auxiliary_project_list.order_id=order_setting.order_id', 'left')->where('order_setting.fast_salary', 2)->where('auxiliary_project_list.capital_id', $item['capital_id'])->value('completion_time');
            $pr[$k]['display'] = !empty($list) ? 1 : 0;
        }
        
        $cap = ['give_money' => $ca['give_money'], 'project_title' => $ca['project_title'], 'gong' => $ca['gong'], 'to_price' => sprintf('%.2f', array_sum(array_column($capital, 'to_price')), 2), 'data' => $pr,];
        return $cap;
    }
    public function ManualSettlement($order_id) {
        // 修正拼写错误：ordesr_id -> order_id
        $envelope = db('envelopes')
            ->where(['ordesr_id' => $order_id, 'type' => 1])
            ->field('give_money,project_title,envelopes_id,gong')
            ->find();
    
        $capitalList = db('capital')
            ->alias('c')
            ->join('detailed d', 'd.detailed_id = c.projectId', 'left')
            ->join('detailed_category dc', 'dc.id = d.detailed_category_id', 'left')
            ->join('unit un', 'un.id = d.un_id', 'left')
            ->field('c.*, d.*, un.title, dc.title as titles, dc.id as category_id')
            ->where([
                'c.ordesr_id' => $order_id,
                'c.types' => 1,
                'c.enable' => 1,
                'c.agency' => 0,
                'c.envelopes_id' => $envelope['envelopes_id']
            ])
            ->select();
    
        $detailedCache = []; // 预处理detailed数据，避免重复查询
        foreach ($capitalList as $item) {
            if ($item['fen'] === 1 && !isset($detailedCache[$item['projectId']])) {
                $detailedCache[$item['projectId']] = db('detailed')
                    ->where('detailed_id', $item['projectId'])
                    ->join('detailed_category dc', 'dc.id = detailed.detailed_category_id', 'left')
                    ->join('unit un', 'un.id = detailed.un_id', 'left')
                    ->field('detailed.*, un.title, dc.title as titles, dc.id')
                    ->find();
            }
        }
        $result = [];
        $orderClearedTime = db('order')->where('order_id', $order_id)->value('cleared_time');

        foreach ($capitalList as $k => $item) {
            $requestedAmount=$item['requested_amount'];
            if( $requestedAmount==0){
                $requestedAmount=$this->bcscale(2,$item['square'] * $item['labor_cost_price']);
            }
            $row = [
                'projectId' => $item['capital_id'],
                'zhi' => $item['zhi'],
                'square' => $item['square'],
                'laborCostReimbursement' =>  $item['labor_cost_reimbursement'],
                'cooperation' => $item['cooperation'],
                'to_price' => empty($item['to_price']) ? 0 : $item['to_price'],
                'categoryName1' => $item['categoryName'],
                'oldLaborCost' => $this->bcscale(2, ($item['square'] * $item['labor_cost_price'])),
                'isEdit' => 0,
                'requestedAmount' => $requestedAmount,
                'display' => db('auxiliary_project_list')
                    ->join('order_setting os', 'os.order_id = auxiliary_project_list.order_id', 'left')
                    ->where([
                        'os.fast_salary' => 2,
                        'auxiliary_project_list.capital_id' => $item['capital_id']
                    ])
                    ->value('completion_time') ? 1 : 0
            ];
    
            // 处理不同fen类型
            switch ($item['fen']) {
                case 1:
                    $detailed = $detailedCache[$item['projectId']] ?? [];
                    $row = array_merge($row, [
                        'projectMoney' => empty($detailed['artificial']) ? 0 : $detailed['artificial'],
                        'projectTitle' => $detailed['detailed_title'],
                        'title' => $detailed['title'],
                        'pris' => $detailed['pris'],
                        'material' => $detailed['material'],
                        'titles' => $detailed['titles'],
                        'id' => $detailed['detailed_id']
                    ]);
    
                    $row['pri'] = $this->calculatePriForFen1($item, $detailed, $orderClearedTime);
                    break;
    
                case 0:
                    $productChan = $this->getProductChanData($item['projectId']);
                    $row = array_merge($row, [
                        'projectMoney' => $productChan['prices'],
                        'projectTitle' => $productChan['product_title'],
                        'title' => $productChan['title'],
                        'pris' => $productChan['materials'],
                        'material' => $item['material'],
                        'titles' => '',
                        'id' => 0
                    ]);
                    $row['pri'] = $item['labor_cost'];
                    break;
    
                case 2:
                case 4:
                    $row = array_merge($row, [
                        'projectMoney' => $item['un_Price'],
                        'projectTitle' => $item['class_b'],
                        'title' => $item['company'],
                        'pris' => '',
                        'material' => $item['material'],
                        'titles' => $item['fen'] === 4 ? $item['titles'] : '',
                        'id' => $item['fen'] === 4 ? $item['detailed_id'] : 0
                    ]);
                    $row['pri'] = $item['labor_cost'];
                    break;
            }
    
            // 处理审批状态
            $approvalRecord = $this->getApprovalRecord($item['capital_id']);
            $row['auditStatus'] = $approvalRecord ? 
                "工费超限申请中，申请金额: {$approvalRecord['change_value']}元" : 
                '';
             
            // 计算上下调金额
            $row = $this->calculateRegulation($row, $approvalRecord);
           
            $result[] = $row;
        }
    
        return [
            'give_money' => $envelope['give_money'],
            'project_title' => $envelope['project_title'],
            'gong' => $envelope['gong'],
            'to_price' =>  $this->bcscale(2, array_sum(array_column($capitalList, 'to_price'))),
            'data' => $result
        ];
    }
    
    /**
     * 计算fen=1时的pri值
     */
    private function calculatePriForFen1($item, $detailed, $orderClearedTime) {
        if ($item['labor_cost'] !== 0.000 || $item['revised'] !== 0 || !empty($orderClearedTime)) {
            return  $this->bcscale(2, $item['labor_cost']);
        }
    
        $insufficient = (float)$detailed['insufficient'];
        $exceed = (float)$detailed['exceed'];
        $exceed1 = (float)$detailed['exceed1'];
        $square = (float)$item['square'];
        $pri = (float)$detailed['pri'];
        $pri1 = (float)$detailed['pri1'];
        $pri2 = (float)$detailed['pri2'];
    
        if ($insufficient > $square) {
            return  $this->bcscale(2, $square * $pri);
        } elseif ($insufficient === $square || ($insufficient < $square && $exceed === 0)) {
            return  $this->bcscale(2, $square * $pri);
        } elseif ($exceed === $square || ($insufficient < $square && $square < $exceed && $pri1 === 0.00)) {
            return  $this->bcscale(2, $square * $pri);
        } elseif ($exceed1 !== 0 && $square > $exceed1) {
            return  $this->bcscale(2, $square * $pri2);
        } elseif ($insufficient === 0 && $exceed !== 0 && $square === $exceed) {
            return  $this->bcscale(2, $square * $pri);
        } elseif ($insufficient === 0 && $exceed !== 0 && $square < $exceed) {
            return  $this->bcscale(2, $square * $pri);
        } elseif ($insufficient === 0 && $exceed === 0 && $exceed1 === 0) {
            return  $this->bcscale(2, $pri);
        } else {
            return  $this->bcscale(2, $square * ($square <= $exceed ? $pri : $pri1));
        }
    }
    
    /**
     * 获取product_chan数据
     */
    private function getProductChanData($productId) {
        return db('product_chan')
            ->alias('pc')
            ->join('unit u', 'pc.units_id = u.id', 'left')
            ->where('product_id', $productId)
            ->field('pc.product_title, pc.prices, u.title, pc.materials')
            ->find() ?: [];
    }
    
    /**
     * 获取审批记录
     */
    private function getApprovalRecord($capitalId) {
        return db('approval_record', config('database.zong'))
            ->where([
                'relation_id' => $capitalId,
                'type' => 6,
                'city_id' => config('cityId'),
                'status' => 0
            ])
            ->order('id desc')
            ->find();
    }
    
    /**
     * 计算上下调金额
     */
    private function calculateRegulation($row, $approvalRecord) {
        $old = (float)$row['oldLaborCost'];
        $current = (float)$row['pri'];
        
        $row['downregulation'] = bcsub($old, $current, 2);
        $row['upRegulation'] = $approvalRecord ? 
            bcsub(bcadd($current, $approvalRecord['change_value'], 2), $old, 2) : 
            0;
    
        // 处理审批状态影响isEdit
        $row['isEdit'] = db('approval', config('database.zong'))
            ->where([
                'relation_id' => $row['projectId'],
                'status' => 0,
                'type' => 8
            ])
            ->find() ? 1 : 0;
    
        return $row;
    }
    
    /**
     * 金额精度处理辅助函数
     */
    private function bcscale($scale, $value) {
        return sprintf("%.{$scale}f", $value);
    }
    
    public static function type($type) {
        switch ($type) {
            case -1:
                $title = "待指派";
                break;
            case 0:
                $title = "待指派";
                break;
            case 1:
                $title = "待接单";
                break;
            case 2:
                $title = "待上门";
                break;
            case 3:
                $title = "待签约";
                break;
            case 4:
                $title = "施工中";
                break;
            case 5:
                $title = "施工中";
                break;
            case 6:
                $title = "已完成";
                break;
            case 7:
                $title = "已完工";
                break;
            case 8:
                $title = "已取消";
                break;
            case 9:
                $title = "退单";
                break;
            default:
                $title = "无效订单";
                break;
        }
        
        return $title;
    }
    
    public function addres($order_id) {
        $list = $this->join('province p', 'order.province_id=p.province_id', 'left')->join('city c', 'order.city_id=c.city_id', 'left')->join('county y', 'order.county_id=y.county_id', 'left')->join('user us', 'order.assignor=us.user_id', 'left')->field('concat(p.province,c.city,y.county,order.addres) as addres,assignor,us.username,us.registrationId')->where('order_id', $order_id)->find();
        return $list;
    }
    
    public function OrderList() {
        return $this->hasMany('Capital', 'ordesr_id', 'order_id')->where('fen', '<>', 4)->where('enable', 1)->where('types', 1)->field('projectId,capital_id,class_a,class_b as  projectTitle,company,square,un_Price as projectMoney,zhi,to_price as allMoney,fen as types,increment,gold_suite as type,agency,acceptance,projectRemark as remarks,approve,approval_reason,concat(capital.reason_for_deduction,if(capital.modified_quantity=0,"",",减量:"),if(capital.modified_quantity=0,"",round(capital.square-capital.modified_quantity,2))) as reasonForDeduction,envelopes_id,categoryName,rule as sectionTitle,capital.modified_quantity,ordesr_id');
    }
    
    /*
     * 订单费
     */
    public static function orderMoney($start) {
        $fei = 120;
        if ($start >= 1643644800) {
            $fei = 200;
        }
        return $fei;
    }
    
    
    public function MyBonus($userId) {
        $list = db('order', config('database.zong'))->join('order_aggregate', 'order_aggregate.order_id=order.order_id', 'left')->join('order_info', 'order_info.order_id=order.order_id', 'left');
        if (!empty($userId['stareTime'])) {
            $start = strtotime(date('Y-m-01 00:00:00', strtotime($userId['stareTime'])));//获取指定月份的第一天
            $end   = strtotime(date('Y-m-t 23:59:59', strtotime($userId['stareTime']))); //获取指定月份的最后一天
            $list->whereBetween('order.created_time', [$start, $end]);
        }
        $data = $list->where('order.entry_user_id', $userId['user_id'])->where('order.entry_type', 1)->field('order.contacts,order.order_id,order.telephone,concat(order_info.channel_title,if(ifnull(order_info.channel_details_title,0)=0," ",concat("-",order_info.channel_details_title))) as title,order.state,FROM_UNIXTIME(order.created_time,"%Y-%m-%d ")as createdTime,order_info.pro_id_title,order_aggregate.total_price as totalPrice,order.hematopoiesis')->select();
        foreach ($data as $k => $item) {
            $myOrderAwardList   = db('my_order_award', config('database.zong'))->where('order_id', $item['order_id'])->where('type', 1)->where('user_id', $userId['user_id'])->field('sum(if(my_order_award.state=1,my_order_award.profit,0)) as adopt,sum(if(my_order_award.state=2,my_order_award.profit,0)) as reject')->select();
            $data[$k]['adopt']  = empty($myOrderAwardList[0]['adopt']) ? 0 : $myOrderAwardList[0]['adopt'];
            $data[$k]['reject'] = empty($myOrderAwardList[0]['reject']) ? 0 : $myOrderAwardList[0]['reject'];
            $data[$k]['type']   = self::type($item['state']);
            
        }
        return $data;
    }
    
    public function UrbanAccess($city_id) {
        
        if ($city_id == 241) {
            $content = config('database.cd');
        } elseif ($city_id == 239) {
            $content = config('database.cq');
        } elseif ($city_id == 262) {
            $content = config('database.gy');
        } elseif ($city_id == 172) {
            $content = config('database.wh');
        } elseif ($city_id == 375) {
            $content = config('database.sh');
        } elseif ($city_id == 202) {
            $content = config('database.sz');
        } elseif ($city_id == 501) {
            $content = config('database.bj');
        } elseif ($city_id == 200) {
            $content = config('database.gz');
        } elseif ($city_id == 205) {
            $content = config('database.fs');
        } elseif ($city_id == 216) {
            $content = config('database.dg');
        }elseif ($city_id == 246) {
            $content = config('database.my');
        }
        return isset($content) ? $content : 0;
    }
    

    
    public function orderType($userId, $type = 0) {
        $list = $this->field('sum(if(order.state>=1 and order.state<=3,1,0)) as documentary,sum(if((order.state=1 or order.undetermined=1) and order.state !=8 and order.state !=9 and order.state !=10 and  order.state !=11,1,0)) as orderToBeReceived,sum(if(order.state=2 and order_times.late_clock_time =0 and order.undetermined =0,1,0)) as stayAtHome,sum(if(order_times.envelopes_time =0  and order.state=3 and order_times.late_clock_time !=0,1,0)) as toBeQuoted, sum(if(order_times.signing_time =0 and order.state=3 and order_times.envelopes_time !=0,1,0)) as toBeSigned,sum(if(order_times.signing_time !=0 and order.state=3 and order_times.envelopes_time !=0,1,0)) as signedButNotCollected,sum(if(order.state>3 and order.state<8 and ((order_aggregate.main_price=0 and order_aggregate.agent_price !=0 and order.settlement_time is  null) or (order_aggregate.main_price !=0 and order_aggregate.agent_price =0 and order.cleared_time is  null) or ((order_aggregate.main_price !=0 and order.cleared_time is  null ) or (order_aggregate.agent_price !=0 and order.settlement_time is null))),1,0)) as beUnderConstructionList,sum(if(order.start_time IS  NULL and order.state=4,1,0)) as toBeStarted,sum(if(order.start_time IS NOT NULL and  order.state=4,1,0)) as beUnderConstruction,
            sum(if(order.state=7 AND (
            CASE
            WHEN order_aggregate.main_price=0 and order_aggregate.agent_price !=0 and order.settlement_time is  null THEN 1
             WHEN order_aggregate.main_price !=0 and order_aggregate.agent_price =0 and order.cleared_time is  null THEN  1
             WHEN order_aggregate.main_price =0 and order_aggregate.agent_price =0 and order.cleared_time is  null and order.settlement_time is null THEN  1
             WHEN (order_aggregate.main_price !=0 and (order.cleared_time is  null or order.cleared_time =0) ) or (order_aggregate.agent_price !=0 and (order.settlement_time is null or order.settlement_time =0 )) THEN 1
             
           ELSE 0 END
              )=1,1,0)) as completionToBeSettled,
            sum(if(order.state=7 AND ( CASE
             WHEN order_aggregate.main_price=0 and order_aggregate.agent_price !=0 and order.settlement_time is Not null THEN 1
             WHEN order_aggregate.main_price !=0 and order_aggregate.agent_price =0 and order.cleared_time is not null THEN  1
              WHEN order_aggregate.main_price =0 and order_aggregate.agent_price =0 and order.cleared_time is not null and order.settlement_time is not null THEN  1
              WHEN order_aggregate.main_price =0 and order_aggregate.agent_price =0 and order.cleared_time is not null and order.settlement_time is  null THEN  1
              WHEN order_aggregate.main_price =0 and order_aggregate.agent_price =0 and order.cleared_time is  null and order.settlement_time is not null THEN  1
             WHEN order_aggregate.main_price !=0 and order_aggregate.agent_price !=0 and order.cleared_time is not null and order.settlement_time is not null THEN 1  ELSE 0 END)=1,1,0)) as closed,sum(if(order.state =8,1,0)) as cancelled,sum(if(order.state=9,1,0)) as chargeback')->join('order_info', 'order.order_id=order_info.order_id', 'left')->join('order_times', 'order.order_id=order_times.order_id', 'left')->join('startup st', 'order.startup_id=st.startup_id', 'left')->join('before be', 'order.before_id=be.before_id', 'left')->join('order_aggregate', 'order.order_id=order_aggregate.order_id', 'left');
        if ($type == 1) {
            $list->where('order.deliverer', $userId);
        } else {
            $list->where('order.assignor', $userId);
        }
        
        $list       = $list->select();
        $reworkList = db('rework_end')->field('sum(if(rework_end.confirmed_time=0 and rework_end.update_time=0 and rework_end.completion_time=0 and order.state=7,1,0)) as gou,sum(if(rework_end.confirmed_time !=0 and rework_end.update_time=0 and rework_end.completion_time=0 and order.state=7,1,0)) as documentary,sum(if(rework_end.confirmed_time !=0 and rework_end.update_time !=0 and rework_end.completion_time =0 and order.state=7,1,0)) as yan,sum(if(rework_end.confirmed_time !=0 and rework_end.update_time !=0 and rework_end.completion_time !=0 and order.state=7,1,0))  as endOrder')->where('rework_end.dispatch_time','>',0)->join('order', 'order.order_id=rework_end.order_id', 'left');
//        if ($type == 1) {
//            $reworkList->where('order.deliverer', $userId);
//        } else {
//            $reworkList->where('order.assignor', $userId);
//        }
        $reworkList->where('rework_end.user_id', $userId);
        $reworkList = $reworkList->select();
        $auto_info=db('order_dispatch_user_auto_info',config('database.zong'))
         ->field('FROM_UNIXTIME(order_dispatch_user_auto_info.create_time,"%Y-%m-%d %H:%i:%s")as createTime,if(reason_type=1,"超时自动","手动") as method,reason')
        ->where('user_id', $userId)
        ->whereIn('reason_type', [1,2,3])
        ->where('create_time', '>=', strtotime('-60 days'))
         ->order('create_time desc')
        ->count();
        $list       = [
            [
                'title' => "跟单",
                'type' => 1,
                'count' => empty($list[0]['documentary']) ? 0 : $list[0]['documentary'],
                'data' => [
                    ['title' => "待接单", 'subordinate' => 1, 'count' => $list[0]['orderToBeReceived']],
                    ['title' => "待上门", 'subordinate' => 2, 'count' => $list[0]['stayAtHome']],
                    ['title' => "待报价", 'subordinate' => 3, 'count' => $list[0]['toBeQuoted']],
                    ['title' => "待签约", 'subordinate' => 4, 'count' => $list[0]['toBeSigned']],
                    ['title' => "已签约款不足", 'subordinate' => 5, 'count' => $list[0]['signedButNotCollected']],

                ]

            ],
            [
                'title' => "施工中",
                'type' => 2,
                'count' => empty($list[0]['beUnderConstructionList']) ? 0 : $list[0]['beUnderConstructionList'],
                'data' => [
                    ['title' => "待开工", 'subordinate' => 1, 'count' => $list[0]['toBeStarted']],
                    ['title' => "施工中", 'subordinate' => 2, 'count' => $list[0]['beUnderConstruction']],
                    ['title' => "完工待结算", 'subordinate' => 3, 'count' => $list[0]['completionToBeSettled']]
                ]

            ],
            [
                'title' => "已完结",
                'type' => 3,
                'count' => $list[0]['closed'] + $list[0]['cancelled'] + $list[0]['chargeback'],
                'data' => [
                    ['title' => "已完结", 'subordinate' => 1, 'count' => $list[0]['closed']],
                    ['title' => "已取消", 'subordinate' => 2, 'count' => $list[0]['cancelled']],
                    ['title' => "已退单", 'subordinate' => 3, 'count' => $list[0]['chargeback']]
                ]
            ],
            [
                'title' => "售后",
                'type' => 4,
                'count' => $reworkList[0]['gou'] + $reworkList[0]['documentary'] + $reworkList[0]['yan'] + $reworkList[0]['endOrder'],
                'data' => [
                    ['title' => "沟通中", 'subordinate' => 1, 'count' => $reworkList[0]['gou']],
                    ['title' => "返工中", 'subordinate' => 2, 'count' => $reworkList[0]['documentary']],
                    ['title' => "客服验收中", 'subordinate' => 3, 'count' => $reworkList[0]['yan']],
                    ['title' => "售后完成", 'subordinate' => 4, 'count' => $reworkList[0]['endOrder']]
                ]
            ],
            [
                'title' => "拒单记录",
                'type' => 0,
                'count' => $auto_info,
                'data' => null


            ]

        ];
        return $list;
    }
    
    public function orderNewList($pid, $type, $page, $limit, $userId, $dataList = [], $pattern = 0) {
        $message = db('order_transfer_record')->field('order_id,create_time,admin_role')->limit(1000)//不加有可能获取的不是最新的一条
            ->order('create_time desc')->buildSql();
        $list    = $this->field('order.order_id,order.point,order.cleared_time,order.settlement_time,order.state,order.acceptance_time,order.undetermined,order.start_time as actualStartTime,order.finish_time as finishTime,order.tui_time as cancellationTime,order.tui_time as chargebackTime,order.finish_time as actualFinishTime,order_aggregate.total_price,order_aggregate.reimbursement_price,order_aggregate.material_agent_price,order_aggregate.reimbursement_agent_price,order_aggregate.material_price,order_aggregate.main_payment_price,order_aggregate.agent_payment_price,order_aggregate.main_price,order_aggregate.agent_price,order.planned,order.contacts,order.telephone,order.hardbound,order_info.pro_id_title as proTitle,order_times.dispatch_time as dispatchTime,order_times.first_clock_time as firstClockTime,order_times.envelopes_time as envelopesTime,order_times.late_clock_time as lateClockTime,order_times.first_through_time as thTime,order_times.late_through_time as lateThTime,order_times.envelopes_first_time as envelopesFirstTime,concat(order_info.county,order.addres) as addres,order_aggregate.payment_price as paymentPrice,order_times.signing_time as contractConTime,st.sta_time as startupTime,st.xiu_id as xiuId,remind.tai,sign.addtime,personal.num,message.create_time as message,message.admin_role,order_setting.partnership_config_id')->join('order_info', 'order.order_id=order_info.order_id', 'left')->join('sign', 'order.order_id=sign.order_id', 'left')->join('personal', 'order.tui_jian=personal.personal_id', 'left')->join('remind', 'order.order_id=remind.order_id and remind.admin_id=order.assignor', 'left')->join('startup st', 'order.startup_id=st.startup_id', 'left')->join('before be', 'order.before_id=be.before_id', 'left')->join('order_aggregate', 'order.order_id=order_aggregate.order_id', 'left')
        ->join([$message => 'message'], 'message.order_id=order.order_id', 'left')
        ->join('order_times', 'order.order_id=order_times.order_id', 'left')->join('order_setting', 'order.order_id=order_setting.order_id', 'left')->order('order_times.dispatch_time desc');
        
        if ($pid == 1 && $type == 1) {
            $list->where(function ($quer) {
                $quer->where('order.state', 1)->whereOr('order.undetermined', 1);
            })->where('order.state', '<>', 8)->where('order.state', '<>', 9)->where('order.state', '<>', 10)->where('order.state', '<>', 11)->order('order_times.dispatch_time desc')->group('order.order_id');;
        } elseif ($pid == 1 && $type == 2) {
            $list->where(['order.state' => 2, 'order.undetermined' => 0, 'order_times.late_clock_time' => 0])->order('order.planned desc')->group('order.order_id');
        } elseif ($pid == 1 && $type == 3) {
            $list->where('order_times.envelopes_time', 0)->where('order_times.late_clock_time', '<>', 0)->where('order.state', 3)->where('order.state', '<>', 8)->where('order.state', '<>', 9)->order('order.order_id desc')->group('order.order_id');
        } elseif ($pid == 1 && $type == 4) {
            $list->where(['order.state' => 3])->where('order_times.envelopes_time', '<>', 0)->where('order_times.signing_time', 0)->order('order.order_id desc')->group('order.order_id');
        } elseif ($pid == 1 && $type == 5) {
            $list->where('order_times.signing_time', '<>', 0)->where('order_times.envelopes_time', '<>', 0)->where(['order.state' => 3])->order('order_times.signing_time desc')->group('order.order_id');;
        } elseif ($pid == 2 && $type == 1) {
            $list->where(['order.state' => 4])->whereNull('order.start_time')->order('order.order_id desc')->group('order.order_id');
        } elseif ($pid == 2 && $type == 2) {
            $list->where(['order.state' => 4])->whereNotNull('order.start_time')->order('order.order_id desc')->group('order.order_id');
        } elseif ($pid == 2 && $type == 3) {
            
            $list->where(['order.state' => 7])->where('CASE
            WHEN order_aggregate.main_price=0 and order_aggregate.agent_price !=0  THEN order.settlement_time is  null
             WHEN order_aggregate.main_price !=0 and order_aggregate.agent_price =0  THEN  order.cleared_time is  null
             WHEN order_aggregate.main_price =0 and order_aggregate.agent_price =0 and (order_aggregate.material_price + order_aggregate.reimbursement_price) =0 and  (order_aggregate.material_agent_price+order_aggregate.reimbursement_agent_price) !=0  THEN  order.settlement_time is  null
             WHEN order_aggregate.main_price =0 and order_aggregate.agent_price =0 and (order_aggregate.material_agent_price+order_aggregate.reimbursement_agent_price) =0 and (order_aggregate.material_price + order_aggregate.reimbursement_price) !=0  THEN  order.cleared_time is  null
             WHEN order_aggregate.main_price =0 and order_aggregate.agent_price =0 and (order_aggregate.material_agent_price + order_aggregate.reimbursement_agent_price ) !=0 and (order_aggregate.material_price + order_aggregate.reimbursement_price ) !=0 THEN  (order.cleared_time is  null or order.cleared_time =0) and  (order.settlement_time is null or order.settlement_time =0)
             WHEN order_aggregate.main_price !=0 and order_aggregate.agent_price !=0 THEN  order.cleared_time is  null or order.cleared_time =0 or order.settlement_time is null or order.settlement_time =0 END')->order('order.finish_time desc')->group('order.order_id');
        } elseif ($pid == 3 && $type == 1) {
            $list->where(['order.state' => 7])->where('CASE
            WHEN order_aggregate.main_price=0 and order_aggregate.agent_price !=0  THEN order.settlement_time is Not null
             WHEN order_aggregate.main_price !=0 and order_aggregate.agent_price =0  THEN  order.cleared_time is Not null
              WHEN order_aggregate.main_price =0 and order_aggregate.agent_price =0 and (order_aggregate.material_agent_price+order_aggregate.reimbursement_agent_price) =0 and (order_aggregate.material_price + order_aggregate.reimbursement_price) =0 THEN  order.cleared_time is Not null or order.settlement_time is Not null
             WHEN order_aggregate.main_price =0 and order_aggregate.agent_price =0 and (order_aggregate.material_agent_price + order_aggregate.reimbursement_agent_price) =0 and (order_aggregate.material_price + order_aggregate.reimbursement_price) !=0 THEN  order.cleared_time is Not null
             WHEN order_aggregate.main_price =0 and order_aggregate.agent_price =0 and (order_aggregate.material_price + order_aggregate.reimbursement_price) =0 and (order_aggregate.material_agent_price + order_aggregate.reimbursement_agent_price) !=0 THEN  order.settlement_time is Not null
             WHEN order_aggregate.main_price =0 and order_aggregate.agent_price =0 and (order_aggregate.material_price + order_aggregate.reimbursement_price) =0  THEN  order.settlement_time is Not null
             WHEN order_aggregate.main_price =0 and order_aggregate.agent_price =0 and  (order.cleared_time is not null or order.cleared_time !=0 ) and  (order.settlement_time is not null or order.settlement_time !=0) THEN  order.cleared_time is Not null and order.settlement_time is Not null
             WHEN order_aggregate.main_price !=0 and order_aggregate.agent_price !=0 THEN  order.cleared_time is Not null and order.settlement_time is Not null END')->order('order.cleared_time desc,order.settlement_time desc')->group('order.order_id');
            
        } elseif ($pid == 3 && $type == 2) {
            $list->where(['order.state' => 8])->order('order.tui_time desc')->group('order.order_id');
        } elseif ($pid == 3 && $type == 3) {
            $list->where(['order.state' => 9])->order('order.tui_time desc')->group('order.order_id');
        } elseif ($pid == 4 && $type == 1) {
            $list->join('rework_end', 'order.order_id=rework_end.order_id', 'right')->where(['order.state' => 7])  ->where('rework_end.update_time', 0)->where('rework_end.confirmed_time',0)->where('rework_end.completion_time',0)->where('rework_end.dispatch_time','>',0)->field('rework_end.created_time as reworkCreatedTime,rework_end.id as reworkId')->order('order.tui_time desc');
        } elseif ($pid == 4 && $type == 2) {
            $list->join('rework_end', 'order.order_id=rework_end.order_id', 'right')->where(['order.state' => 7])
                ->where('rework_end.update_time', 0)
             ->where('rework_end.confirmed_time','<>',0)->where('rework_end.completion_time',0)->where('rework_end.dispatch_time','>',0)->field('rework_end.created_time as reworkCreatedTime,rework_end.id as reworkId')->order('rework_end.created_time desc');
        } elseif ($pid == 4 && $type == 3) {
            $list->join('rework_end', 'order.order_id=rework_end.order_id', 'right')->where(['order.state' => 7])  ->where('rework_end.update_time', '<>',0)->where('rework_end.confirmed_time','<>',0)->where('rework_end.completion_time',0)->field('rework_end.created_time as reworkCreatedTime,rework_end.id as reworkId')->where('rework_end.dispatch_time','>',0)->order('rework_end.update_time desc');
        } elseif ($pid == 4 && $type == 4) {
            $list->join('rework_end', 'order.order_id=rework_end.order_id', 'right')->where(['order.state' => 7])->where('rework_end.update_time', '<>',0)->where('rework_end.confirmed_time','<>',0)->where('rework_end.completion_time','<>',0)->field('rework_end.created_time as reworkCreatedTime,rework_end.id as reworkId')->where('rework_end.dispatch_time','>',0)->order('rework_end.completion_time desc');
        } elseif ($pid == 0) {
            
            $where = [];
            $list->where('state', '<>', 0)->where('state', '<>', 10)->group('order.order_id');
            if (isset($dataList['point']) && $dataList['point'] != 0) {
                $list->where('order.point', 2)->where('order.assignor', $userId);
                $where['order.point']    = ['=', 2];
                $where['order.assignor'] = ['=', $userId];
            }
            
            if (isset($dataList['orderCreationStart']) && $dataList['orderCreationStart'] != 0 && isset($dataList['orderCreationEnd']) && $dataList['orderCreationEnd'] != 0) {
                if (isset($dataList['clockIn']) && $dataList['clockIn'] == 1) {
                    $reserve = \db('user')->where('user_id', $userId)->value('reserve');
                    if ($reserve == 2) {
                        $where['order.assignor'] = ['=', $userId];
                    }
                    $orderCreationStart = strtotime($dataList['orderCreationStart'] . " 00:00");
                    $orderCreationEnd   = strtotime($dataList['orderCreationEnd'] . " 23:59");
                    $list->whereBetween('order.created_time', [$orderCreationStart, $orderCreationEnd]);
                    $where['order.created_time'] = ['Between', [$orderCreationStart, $orderCreationEnd]];
                } else {
                    $orderCreationStart = strtotime($dataList['orderCreationStart'] . " 00:00");
                    $orderCreationEnd   = strtotime($dataList['orderCreationEnd'] . " 23:59");
                    $list->whereBetween('order.created_time', [$orderCreationStart, $orderCreationEnd])->where('order.assignor', $userId);
                    $where['order.created_time'] = ['Between', [$orderCreationStart, $orderCreationEnd]];
                    $where['order.assignor']     = ['=', $userId];
                }
                
            }
            if (isset($dataList['doorToDoorPunchStart']) && $dataList['doorToDoorPunchStart'] != 0 && isset($dataList['doorToDoorPunchEnd']) && $dataList['doorToDoorPunchEnd'] != 0) {
                if (isset($dataList['clockIn']) && $dataList['clockIn'] == 1) {
                    $reserve = \db('user')->where('user_id', $userId)->value('reserve');
                    if ($reserve == 2) {
                        $where['order.assignor'] = ['=', $userId];
                    }
                    $doorToDoorPunchStart = strtotime($dataList['doorToDoorPunchStart'] . " 00:00");
                    $doorToDoorPunchEnd   = strtotime($dataList['doorToDoorPunchEnd'] . " 23:59");
                    $list->whereBetween('order_times.late_clock_time', [$doorToDoorPunchStart, $doorToDoorPunchEnd]);
                    $where['order_times.late_clock_time'] = ['Between', [$doorToDoorPunchStart, $doorToDoorPunchEnd]];
                    
                } else {
                    $doorToDoorPunchStart = strtotime($dataList['doorToDoorPunchStart'] . " 00:00");
                    $doorToDoorPunchEnd   = strtotime($dataList['doorToDoorPunchEnd'] . " 23:59");
                    $list->whereBetween('order_times.late_clock_time', [$doorToDoorPunchStart, $doorToDoorPunchEnd])->where('order.assignor', $userId);
                    $where['order_times.late_clock_time'] = ['Between', [$doorToDoorPunchStart, $doorToDoorPunchEnd]];
                    $where['order.assignor']              = ['=', $userId];
                }
                
            }
            if (isset($dataList['signAContractStart']) && $dataList['signAContractStart'] != 0 && isset($dataList['signAContractEnd']) && $dataList['signAContractEnd'] != 0) {
                if (isset($dataList['clockIn']) && $dataList['clockIn'] == 1) {
                    $reserve = \db('user')->where('user_id', $userId)->value('reserve');
                    if ($reserve == 2) {
                        $where['order.assignor'] = ['=', $userId];
                    }
                    $signAContractStart = strtotime($dataList['signAContractStart'] . " 00:00");
                    $signAContractEnd   = strtotime($dataList['signAContractEnd'] . " 23:59");
                    $list->whereBetween('order_times.signing_time', [$signAContractStart, $signAContractEnd]);
                    $where['order_times.signing_time'] = ['Between', [$signAContractStart, $signAContractEnd]];
                } else {
                    $signAContractStart = strtotime($dataList['signAContractStart'] . " 00:00");
                    $signAContractEnd   = strtotime($dataList['signAContractEnd'] . " 23:59");
                    $list->whereBetween('order_times.signing_time', [$signAContractStart, $signAContractEnd])->where('order.assignor', $userId);
                    $where['order_times.signing_time'] = ['Between', [$signAContractStart, $signAContractEnd]];
                    $where['order.assignor']           = ['=', $userId];
                }
            }
            if (isset($dataList['settlementStart']) && $dataList['settlementStart'] != 0 && isset($dataList['settlementEnd']) && $dataList['settlementEnd'] != 0) {
                if (isset($dataList['clockIn']) && $dataList['clockIn'] == 1) {
                    $reserve = \db('user')->where('user_id', $userId)->value('reserve');
                    if ($reserve == 2) {
                        $where['order.assignor'] = ['=', $userId];
                    }
                    $settlementStart = strtotime($dataList['settlementStart'] . "00:00");
                    $settlementEnd   = strtotime($dataList['settlementEnd'] . " 23:59");
                    $list->whereBetween('order.cleared_time', [$settlementStart, $settlementEnd]);
                    $where['order.cleared_time'] = ['Between', [$settlementStart, $settlementEnd]];
                } else {
                    $settlementStart = strtotime($dataList['settlementStart'] . "00:00");
                    $settlementEnd   = strtotime($dataList['settlementEnd'] . " 23:59");
                    $list->whereBetween('order.cleared_time', [$settlementStart, $settlementEnd])->where('order.assignor', $userId);
                    $where['order.cleared_time'] = ['Between', [$settlementStart, $settlementEnd]];
                    $where['order.assignor']     = ['=', $userId];
                }
            }
            if (isset($dataList['keywords']) && $dataList['keywords'] != '') {
                if (isset($dataList['clockIn']) && $dataList['clockIn'] == 1) {
                    $reserve = \db('user')->where('user_id', $userId)->value('reserve');
                    if ($reserve == 2) {
                        $where['order.assignor'] = ['=', $userId];
                    }
                    $list->where(['order.contacts|order.telephone|order.addres|order.order_no|order_info.community|order_info.quarters|order_info.residential|order_info.personal|order_info.property' => ['like', "%{$dataList['keywords']}%"]]);
                    $where['order.contacts|order.telephone|order.addres|order.order_no|order_info.community|order_info.quarters|order_info.residential|order_info.personal|order_info.property'] = ['like', "%{$dataList['keywords']}%"];
                    
                } else {
                    $list->where(['order.contacts|order.telephone|order.addres|order.order_no|order_info.community|order_info.quarters|order_info.residential|order_info.personal|order_info.property' => ['like', "%{$dataList['keywords']}%"]])->where('order.assignor', $userId);
                    $where['order.contacts|order.telephone|order.addres|order.order_no|order_info.community|order_info.quarters|order_info.residential|order_info.personal|order_info.property'] = ['like', "%{$dataList['keywords']}%"];
                    $where['order.assignor']                                                                                                                                                     = ['=', $userId];
                }
                
            }
            
            if (isset($dataList['contractedAmountOfMoneyStart']) && $dataList['contractedAmountOfMoneyStart'] != 0 && isset($dataList['contractedAmountOfMoneyEnd']) && $dataList['contractedAmountOfMoneyEnd'] != 0) {
                if (isset($dataList['clockIn']) && $dataList['clockIn'] == 1) {
                    $reserve = \db('user')->where('user_id', $userId)->value('reserve');
                    if ($reserve == 2) {
                        $where['order.assignor'] = ['=', $userId];
                    }
                    $list->whereBetween('order_aggregate.total_price', [$dataList['contractedAmountOfMoneyStart'], $dataList['contractedAmountOfMoneyEnd']]);
                    $where['order_aggregate.total_price'] = ['Between', [$dataList['contractedAmountOfMoneyStart'], $dataList['contractedAmountOfMoneyEnd']]];
                } else {
                    $list->whereBetween('order_aggregate.total_price', [$dataList['contractedAmountOfMoneyStart'], $dataList['contractedAmountOfMoneyEnd']])->where('order.assignor', $userId);
                    $where['order_aggregate.total_price'] = ['Between', [$dataList['contractedAmountOfMoneyStart'], $dataList['contractedAmountOfMoneyEnd']]];
                    $where['order.assignor']              = ['=', $userId];
                }
            }
            if (isset($dataList['orderId']) && $dataList['orderId'] != 0) {
                $list->whereIn('order.order_id', $dataList['orderId']);
                $where['order.order_id'] = ['in', $dataList['orderId']];
            }
            $list->order('order.order_id desc');
            
        }
        if ($pid != 0) {
            if ($pattern == 1 && $pid !=4) {
                $list->where('order.deliverer', $userId);
            } elseif($pid==4) {
                $list->where('rework_end.user_id', $userId);
            }else {
                $list->where('order.assignor', $userId);
            }
        }else{
            $list->where('order.assignor', $userId); 
            $where['order.assignor']              = ['=', $userId];
        }
      
        $listArray = $list->page($page, $limit)->select();
        if ($pid == 0) {
            $mode = db('order')->field('order.order_id,order.cleared_time,order.settlement_time,order.state,order.acceptance_time,order.undetermined,order.start_time as actualStartTime,order.finish_time as finishTime,order.tui_time as cancellationTime,order.tui_time as chargebackTime,order.finish_time as actualFinishTime,order_aggregate.total_price,order_aggregate.main_payment_price,order_aggregate.agent_payment_price,order_aggregate.main_price,order_aggregate.agent_price,order.planned,order.contacts,order.telephone,order.hardbound,order_info.pro_id_title as proTitle,order_times.dispatch_time as dispatchTime,order_times.first_clock_time as firstClockTime,order_times.envelopes_time as envelopesTime,order_times.late_clock_time as lateClockTime,order_times.first_through_time as thTime,order_times.late_through_time as lateThTime,order_times.envelopes_first_time as envelopesFirstTime,concat(order_info.county,order.addres,order.street,order.building,order.unit,order.room) as addres,order_aggregate.payment_price as paymentPrice,order_times.signing_time as contractConTime,st.sta_time as startupTime,st.xiu_id as xiuId,remind.tai,sign.addtime,personal.num,order_setting.partnership_config_id')->join('order_info', 'order.order_id=order_info.order_id', 'left')->join('personal', 'order.tui_jian=personal.personal_id', 'left')->join('sign', 'order.order_id=sign.order_id', 'left')->join('remind', 'order.order_id=remind.order_id and remind.admin_id=order.assignor', 'left')->join('startup st', 'order.startup_id=st.startup_id', 'left')->join('before be', 'order.before_id=be.before_id', 'left')->join('order_aggregate', 'order.order_id=order_aggregate.order_id', 'left')->join('order_times', 'order.order_id=order_times.order_id', 'left')->join('order_setting', 'order.order_id=order_setting.order_id', 'left')->where('state', '<>', 0)->where('state', '<>', 10);
            if (!empty($where)) {
                $mode->where($where);
            }
            $count = $mode->group('order.order_id')->count();
        }
        $listData = [];
        foreach ($listArray as $k => $item) {
            $listData[$k]['order_id']  = $item['order_id'];
            $listData[$k]['contacts']  = $item['contacts'];
            $listData[$k]['telephone'] = substr($item['telephone'], 0, 3). '*****'. substr($item['telephone'], -3);
            $listData[$k]['point']     = $item['point'];
            $listData[$k]['message']   = 0;
            if (!empty($item['admin_role'])) {
                if ($item['admin_role'] == 1) {
                    $listData[$k]['message'] = 2;
                } elseif ($item['admin_role'] == 2 || $item['admin_role'] == 3) {
                    $listData[$k]['message'] = 1;
                }
            }
            $transfer_record_confirm=db('transfer_record_confirm')->where('order_id',$item['order_id'])->where('confirm',0)->find();
            $thirtyDaysAgo = time() - 30 * 86400;
            $clock_in_store = db('envelopes')
                ->alias('e')
                ->join('clock_in_store cis', 'cis.order_id = e.ordesr_id', 'left')
                ->whereNull('cis.id')  // 假设clock_in_store的主键是id，而非ordesr_id
                ->where('e.ordesr_id', $item['order_id'])
                ->where('e.total_price', '>=', 30000)
                ->where('e.created_time', '>=', $thirtyDaysAgo)
                ->where('e.delete_time', 0)
                ->field([
                    'e.envelopes_id',
                    'e.ordesr_id',
                    'e.project_title',
                    'e.total_price',
                    'e.created_time',
                    Db::raw("FLOOR((UNIX_TIMESTAMP(NOW()) - e.created_time) / 86400) AS quote_days")
                ])
                ->order('e.created_time DESC')
                ->select();
                 $listData[$k]['clockInStore']='';
                if($item['contractConTime']==0){
                    $listData[$k]['clockInStore'] =empty($clock_in_store)?'':"此单需邀约客户到店（已报价".$clock_in_store[0]['quote_days'].'天），请及时邀约';
                }
            
            $listData[$k]['transferRecordOrder'] =empty($transfer_record_confirm)?0:1;
            //金装
            $listData[$k]['hardbound'] = $item['hardbound'];
            $listData[$k]['proTitle']  = $item['proTitle'];
            $listData[$k]['addres']    = $item['addres'];
            $partnership_config        = Db::connect(config('database.zong'))->table('partnership_config')->where('id', $item['partnership_config_id'])->find();
            $listData[$k]['tag']       = $partnership_config['tag'];
//            $listData[$k]['shell']  = 1;
            $judgeList = $this->judge($item, $pid);
            if ($pid == 4) {
                if (!empty($item['chargebackTime'])) {
                    $judgeList['creationTime'] = !empty($item['chargebackTime']) ? "创建时间：" . date('Y-m-d H:i:s', $item['chargebackTime']) : '';
                } elseif (!empty($item['reworkCreatedTime'])) {
                    //创建时间
                    $judgeList['creationTime'] = !empty($item['reworkCreatedTime']) ? "创建时间：" . date('Y-m-d H:i:s', $item['reworkCreatedTime']) : '';
                    
                } elseif (!empty($item['reworkUpdateTime'])) {
                    //退单时间
                    $judgeList['creationTime'] = !empty($item['reworkUpdateTime']) ? "结案时间：" . date('Y-m-d H:i:s', $item['reworkUpdateTime']) : '';
                    
                    
                }
                $listData[$k]['reworkId'] = $item['reworkId'];
                $listData[$k]['order_id'] = $item['reworkId'];
            }
            if($pid==1){
                $listData[$k]['through']=db('through')->where('order_ids',$item['order_id'])->where('role',2)->where('admin_id',$userId)->field('FROM_UNIXTIME(th_time,"%Y-%m-%d %H:%i:%s")as thTime,remar')->order('through_id desc')->find();
            }
            $listData[$k]['creationTime'] = $judgeList['creationTime'];
            $listData[$k]['tips']         = $judgeList['tips'];
            $listData[$k]['remind']       = $judgeList['remind'];
            $listData[$k]['pending']      = $judgeList['pending'];
        }
        if ($pid == 0) {
            return ['data' => $listData, 'count' => $count];
        } else {
            return $listData;
        }
        
    }
    
    public function info($orderId,$userInfo) {
        $list        = $this->field('order.order_id,order.channel_details,order.entry,order.pro_id2,order.attributions,order.agency_finish_time,order.building,order.unit,order.room,order.reason,order.acceptance_time,order.point,order.planned,order.undetermined,order.start_time as actualStartTime,order.finish_time as finishTime,order.cleared_time,order.settlement_time,order.state,FROM_UNIXTIME(order.created_time,"%Y-%m-%d %H:%i:%s")as createdTime,order.hardbound,order.pro_id,order.remarks,order.logo,order.contacts,order.order_no,order_info.channel_title as channelTitle,order.telephone,concat(order_info.pro_id_title,"-",order_info.pro_id1_title,"-",order_info.pro_id2_title) as proIdTitle,concat(order_info.county,order.addres) as addres,order.addres as detailedAddress,if(order.sex=1,"男","女") as sex,if(order.new_or_oldUser=1,"新用户","老用户") as newOrOldUser,order_times.receive_time,order_aggregate.payment_price as paymentPrice,order_aggregate.main_payment_price,order_aggregate.agent_payment_price,order_aggregate.material_price,order_aggregate.material_agent_price,order_aggregate.reimbursement_price,order_aggregate.reimbursement_agent_price,order_aggregate.total_price,order_aggregate.main_price,order_aggregate.agent_price,order_times.signing_time as contractConTime,order_times.envelopes_first_time as envelopesFirstTime,order_times.envelopes_time as envelopesTime,order_times.late_clock_time as lateClockTime,order_times.late_through_time as lateThTime,order_times.dispatch_time as dispatchTime,order_setting.new_warranty_card as newWarranty,contract.contracType,contract.contract,contract.main_material_img,personal.num,if(order_setting.sign_type=1,0,1) as sign_type,order_setting.partnership_config_id,order_info.assignor,order_times.turn_time,order_times.first_clock_time as firstClocktime')->join('personal', 'order.tui_jian=personal.personal_id', 'left')->join('contract', 'order.order_id=contract.orders_id', 'left')->join('order_setting', 'order.order_id=order_setting.order_id', 'left')->join('order_info', 'order.order_id=order_info.order_id', 'left')->join('order_aggregate', 'order.order_id=order_aggregate.order_id', 'left')->join('order_times', 'order.order_id=order_times.order_id', 'left')->where('order.order_id', $orderId)->find();
        $list['tai'] = 0;
        
        $judgeList                      = $this->judge($list);
        $list['encryptedPhone'] = $list['telephone'];
        if(preg_match('/^\d{11}$/', 12121212111) ==1){
            $list['telephone'] = substr($list['telephone'], 0, 3). '*****'. substr($list['telephone'], -3);
        }
        $list['originalUserName'] = \db('order_transfer_record')->where('order_transfer_record.order_id',$orderId)->join('user','user.user_id=order_transfer_record.original_user_id','left')->order('order_transfer_record.id desc')->value('user.username');
        $list['angeState']              = 0;
        $list['collisionReminder']      = null;
        $list['collisionReminderState'] = 0;
        $partnership_config             = Db::connect(config('database.zong'))->table('partnership_config')->where('id', $list['partnership_config_id'])->find();
        $order_extend_info              = db('order_extend_info')->where('order_id', $orderId)->find();
        $list['tag']                    = $partnership_config['tag'];
        $order_unique_code=Db::connect(config('database.zong'))->table('order_unique_code')->where('order_id', $orderId)->find();
        $list['isCrowd'] =!empty($order_unique_code)?$order_unique_code['is_crowd']:0;
        $Plate                          = (new Common)->licensePlate(config('cityId'));
        $list['encryptionOrderId']      = $Plate . $partnership_config['tag'] . '·' . $list['detailedAddress'] . '·' . $list['contacts'] . '#' . enPersonalId($orderId);
        if(!empty($order_unique_code)){
            $list['encryptionOrderId'] =$order_unique_code['code'];
        }
         $list['clockIn']=Db::connect(config('database.db2'))->table('clock_in')->where('order_id', $orderId)->where('type', 2)  ->limit(1) ->count() > 0 ? 1 : 0;
         $list['through'] = db('through')->where(['order_ids' => $orderId])->where('mode',"客户需求与方案报告") ->limit(1) ->count() > 0 ? 1 : 0;
         $list['throughShare'] = db('through_share')->where(['order_id' => $orderId]) ->limit(1)  ->count() > 0 ? 1 : 0;
         $list['playWindow'] ="";
        if ($list['state'] < 4 &&  $list['through']==0  && ($list['dispatchTime']>1763654400 || $list['turn_time']>1763654400) && $userInfo['through_inspection']==1) {
            $list['playWindow'] ="上门后，未完善上门基检报告，请及时补充'
标准流程:
1、上门扫码打卡
编辑分享上门基检报告和方案给客户3、客户确认需求后，基于方案完成报价
稍后补充
去补充";
        }
        //是否展示上门基检报告未完成
        $list['displayAndShare']=0;
        if ( ($list['dispatchTime']>1763654400 || $list['turn_time']>1763654400) && $list['state'] < 4 && $userInfo['through_inspection']==1) {
            $list['displayAndShare']=1;
        }
        //是否展示箱单详情弹窗有效上门检测描述vm.baseInfo.value?.throughShare != 1 && vm.baseInfo.value?.displayAndShare == 1
        $list['throughInspection']=$userInfo['through_inspection'];
       $channel_level=getBatchGetRealtimeOrderLevel($orderId);
       $list['orderLevel'] = isset($channel_level['data'][0]['realtime_order_level'])?$channel_level['data'][0]['realtime_order_level']:'';
       $clock_in_store_name=Db::connect(config('database.zong'))->table('clock_in_store')->where('order_id',$orderId)->order('punch_clock desc')->value('punch_clock');
       $list['clockInStoreTime'] = empty($clock_in_store_name)?'':date('Y-m-d H:i:s',$clock_in_store_name);
        if ((($list['building'] == '' && $order_extend_info['building_no'] == 0) && ($list['unit'] == '' && $order_extend_info['unit_no'] == 0) || $list['room'] == '' || empty($order_extend_info)) && $list['contractConTime'] == 0) {
            $list['collisionReminder']      = '该订单暂无门牌号，可能导致撞单，请与客户确认详细地址后补充';
            $list['collisionReminderState'] = 1;
        } else {
            $partnership_config = Db::connect(config('database.zong'))->table('order_similar_record')->where('order_ida', $orderId)->where('order_idb', '>', 0)->where('deleted_ts', 0)->select();
            if (!empty($partnership_config)) {
                $list['collisionReminder'] = '当前订单有撞单风险，请等待售前确认';
            }
        }
        if ($order_extend_info['building_no'] == 1) {
            $list['building'] = 'noBuildingNumber';
        }
        if ($order_extend_info['unit_no'] == 1) {
            $list['unit'] = 'noBuildingNumber';
        }
        $list['isNeedPaper'] = $list['sign_type'];
        //不展示代沟状态
        if ($list['state'] < 4) {
            $list['angeState'] = 0;
        } elseif ($list['state'] > 3 && $list['state'] < 8) {
            if ($list['agent_price'] != 0) {
                //待开工
                $list['angeState'] = 1;
            }
            if (!empty($list['acceptance_time'])) {
                //已验收
                $list['angeState'] = 2;
            }
            if (!empty($list['agency_finish_time'])) {
                //已结算
                $list['angeState'] = 3;
            }
            if (!empty($list['settlement_time'])) {
                //已结算
                $list['angeState'] = 4;
            }
        }
        
        if ($list['contracType'] == 1) {
            $list['contract']          = empty($list['contract']) ? null : unserialize($list['contract']);
            $list['main_material_img'] = empty($list['main_material_img']) ? null : unserialize($list['main_material_img']);
        } else {
            $list['contract']          = null;
            $list['main_material_img'] = null;
        }
        //判断
        if (empty($list['cleared_time']) && $list['main_price'] != 0 && $list['agent_price'] != 0 && empty($list['settlement_time'])) {
            $list['agencyCount'] = 1;
        } elseif (empty($list['cleared_time']) && $list['main_price'] != 0 && $list['agent_price'] == 0) {
            $list['agencyCount'] = 2;
        } elseif (!empty($list['cleared_time']) && $list['main_price'] != 0 && $list['agent_price'] != 0 && empty($list['settlement_time'])) {
            $list['agencyCount'] = 3;
        } elseif ($list['main_price'] == 0 && $list['agent_price'] != 0 && empty($list['settlement_time'])) {
            $list['agencyCount'] = 3;
        } elseif (empty($list['cleared_time']) && $list['main_price'] != 0 && $list['agent_price'] != 0 && !empty($list['settlement_time'])) {
            $list['agencyCount'] = 2;
        } elseif (!empty($list['cleared_time']) && $list['main_price'] != 0 && $list['agent_price'] != 0 && !empty($list['settlement_time'])) {
            $list['agencyCount'] = 4;
        }
        $order_completion=null;
       $order_completion_pass=Db::connect(config('database.zong'))->table('order_completion')->where('order_id',$list['order_id'])->where('inspection_type',3)->find();
         if(empty($order_completion_pass)){
            $order_completion=Db::connect(config('database.zong'))->table('order_completion')->where('order_id',$list['order_id'])->where('inspection_type',2)->field('inspection_type,deadline_time,issue_images as img,inspection_failure_reason as reason,inspection_failure_content as content,id')->order('id desc')->find();
         }
        $list['orderCompletion']=new \stdClass();
        if($judgeList['stateTitle']=='施工中' && !empty($order_completion)){
            if($order_completion['inspection_type']==2){
                $judgeList['stateTitle']  = '施工中'.'(整改期)';
                $order_completion['img']=json_decode($order_completion['img'],true);
                
                $acceptance_issue=db('acceptance_issue',config('database.zong'))->where(['order_completion_id'=>$order_completion['id']])->find();
                $list['orderCompletion']=empty($acceptance_issue)?$order_completion:new \stdClass;
            }
           
        }
        $list['deadlineTime']     = !empty($order_completion)?date('Y-m-d H:i:s',$order_completion['deadline_time']):'';
        $list['subordinate']     = $judgeList['subordinate'];
        $list['stateTitle']      = $judgeList['stateTitle'];
        $list['logo']            = !empty($list['logo']) ? unserialize($list['logo']) : null;
        $list['isNewOrder']      = !empty($list['receive_time']) ? 0 : 1;
        $list['intendedProduct'] = db('order_products_info')->where(['order_id' => $list['order_id']])->value('products_title');
        $order_delay_deduction_note = db('order_delay_deduction_note',config('database.zong'))->where(['order_id' => $list['order_id']])->where('delete_time',0)->order('create_time desc')->find();
     
        $list['extension']='';
        $list['link']='';
        if($order_delay_deduction_note['deduction_money'] >0){
           
             $list['extension']='根据制度2.1规则【延期1天扣款100，t+2执行，最多扣除1/10】此订单延期'.$order_delay_deduction_note['delay_day_2'].'天结算，故扣款'.$order_delay_deduction_note['deduction_money'].'元会在工资中体现';
                // $list['link'] = 'http://api.shopowner.yiniao.cc/Webpage/index.html';
       
        }
        $list['personality']     = db('order_personality', config('database.zong'))->where(['order_id' => $list['order_id']])->field('title,subhead')->select();
        $list['orderCollection'] = 3;
        if ($list['attributions'] == 2) {
            $order_collection        = db('order_collection', config('database.zong'))->where(['order_id' => $list['order_id']])->count();
            $list['orderCollection'] = empty($order_collection) ? 1 : 2;
        }
        $customers = db('customers', config('database.zong'))->field('if(if(customers_vip.vip_expire_time_start  <= unix_timestamp() and customers_vip.vip_expire_time_end>=unix_timestamp(),1,0)=1,1,0)as title')->join('customers_vip', 'customers_vip.customers_id=customers.customers_id', 'left')->where('customers.mobile', $list['telephone'])->find()['title'];
        //跳转签证单页面
        $list['visa'] = 2;
//        if (strtotime($list['createdTime']) > 1660150844 && $list['isNeedPaper'] == 0) {
//            $list['visa'] = 2;
//        }
        $list['isVip'] = empty($customers) ? 0 : $customers;
//        $productsFamilys = db('products_family', config('database.zong'))
//            ->field('products.id,products.products_title')
//            ->join('products', 'products_family.id=products.products_family_id', 'left')
//            ->join('products_restricted_city', 'products_restricted_city.products_id=products.id', 'left')
//            ->join([\db('products_family_category', config('database.zong'))->group('products_category,products_family_id')->buildSql() => 'products_family_category'], 'products_family.id=products.products_family_id', 'right')
//            ->where('products_family_category.products_category', $list['pro_id'])
//            ->where('products.status', 1)
//            ->where('products_restricted_city.city_id', config('cityId'))
//            ->group('products.id')
//            ->select();
//
//        $products_spec = db('products_spec', config('database.zong'))->field('products_spec_title,round(products_spec_price/100,2) as money,scheme_id,products_id,id as only')->select();
//
//        $productsFamilyList = [];
//
//        foreach ($productsFamilys as $k => $item) {
//            $productsSpec = [];
//            foreach ($products_spec as $v) {
//                if ($v['products_id'] == $item['id']) {
//                    $productsSpec[] = $v;
//                }
//            }
//
//
//            if (count($productsSpec) == 1) {
//                $productsFamilyList[$k]['money'] = min(array_column($productsSpec, 'money'));
//            } else {
//                $productsFamilyList[$k]['money'] = min(array_column($productsSpec, 'money')) . '~~~' . max(array_column($productsSpec, 'money'));
//            }
//            $productsFamilyList[$k]['products_id']         = $item['id'];
//            $productsFamilyList[$k]['productsFamilyTitle'] = $item['products_title'];
//            $productsFamilyList[$k]['uniqueNumber']        = date('Ymdhi') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8) . $k;
//
//        }
//
//        $list['productsFamilyList'] = $productsFamilyList;
        
        
        return $list;
    }
    
    public function orderAdministration($orderId) {
        $list = \db('order_aggregate')->field('order_aggregate.main_price,order_aggregate.agent_price,order_aggregate.main_payment_price,order_aggregate.agent_payment_price,order_aggregate.total_price,order_aggregate.main_payment_ok_price,order_aggregate.agent_payment_ok_price,round(order_aggregate.main_price-order_aggregate.main_payment_price,2) as masterContractCollection,round(order_aggregate.main_payment_price-order_aggregate.main_payment_ok_price,2) as  masterContractUnderReview,round(order_aggregate.agent_price-order_aggregate.agent_payment_price,2) as agentPurchaseContractCollection,round(order_aggregate.agent_payment_price-order_aggregate.agent_payment_ok_price,2) as  agentPurchaseContractUnderReview,order_setting.new_warranty_card,order_info.assignor')->join('order_setting', 'order_aggregate.order_id=order_setting.order_id', 'left')->join('order_info', 'order_setting.order_id=order_info.order_id', 'left')->where('order_aggregate.order_id', $orderId)->find();
        //收款记录
        
        $list['masterContractHasBeenRecorded'] = 0;
        if ($list['main_price'] != 0.00) {
            $list['masterContractHasBeenRecorded'] = sprintf("%.2f", ($list['main_payment_ok_price'] / $list['main_price']) * 100);
        }
        $list['agentPurchaseContractHasBeenRecorded'] = 0;
        if ($list['agent_price'] != 0.00) {
            $list['agentPurchaseContractHasBeenRecorded'] = sprintf("%.2f", ($list['agent_payment_ok_price'] / $list['agent_price']) * 100);
        }
        $list['overallProgress'] = $list['main_payment_price'] + $list['agent_payment_price'] . '/' . $list['total_price'];
        
        //沟通记录
        $list['through'] = db('through')->where(['order_ids' => $orderId])->join('user', 'user.user_id=through.admin_id', 'left')->field('if(role=1,"客服",user.username) as username,remar,FROM_UNIXTIME(th_time,"%Y-%m-%d %H:%i:%s") as th_time')->order('through.through_id desc')->limit(2)->select();
        //签证单
        
        $list['visaForm'] = db('visa_form')->join('order', 'order.order_id=visa_form.order_id', 'left')->join('personal', 'order.tui_jian=personal.personal_id', 'left')->where(['visa_form.order_id' => $orderId])->field('FROM_UNIXTIME(visa_form.creation_time,"%Y-%m-%d %H:%i:%s") as creationTime,id,
        if(ifNull(visa_form.signing_time,0) !=0,"已签","未签") as sign')->order('id desc')->select();
        
        //合同
        $sign = db('sign')->where(['order_id' => $orderId])->field('FROM_UNIXTIME(con_time,"%Y-%m-%d %H:%i:%s") as creationTime,sign_id,autograph')->find();
        if (!empty($sign['autograph'])) {
            $sign['title'] = "已签约";
        }
        $list['sign'] = $sign;
        
        
        //报价历史
        $Envelopes     = new  Envelopes();
        $envelopesList = [];
        $Warranty      = null;
        $envelopes     = $Envelopes->where(['ordesr_id' => $orderId])->where('delete_time', 0)->select();
        
        foreach ($envelopes as $k => $l) {
            $to_price = 0;
            if ($l['type'] == 1) {
                $capitalList = $l->CapitalList;
            } else {
                $capitalList = $l->CapitalDatas;
            }
            foreach ($capitalList as $m) {
                
                if ($m['products'] == 1 && $m['products_v2_spec'] != 0 && $m['is_product_choose'] == 1 && $m['typess'] == 1) {
                    $to_price += $m['allMoney'];
                }
                if ($m['products'] == 0 && $m['typess'] == 1) {
                    $to_price += $m['allMoney'];
                }
                if ($m['products'] == 1 && $m['products_v2_spec'] == 0 && $m['typess'] == 1) {
                    $to_price += $m['allMoney'];
                    
                }
            }
            
            $WarrantyList = [];
            
            foreach ($l['capital_datas'] as $m) {
                if ($m['zhi'] == 1 && $m['enable'] == 1) {
                    $WarrantyList['data'][]       = $m;
                    $WarrantyList['created_time'] = !empty($l['created_time']) ? date('Y-m-d H:i:s', $l['created_time']) : '';
                }
                
            }
            if (!empty($WarrantyList)) {
                
                $Warranty = $WarrantyList;
            }
            if (empty($sign['autograph'])) {
                $l['give_money']          = $l['give_money'] - $l['main_round_discount'];
                $l['purchasing_discount'] = $l['purchasing_discount'] - $l['purchasing_round_discount'];
            }
            $envelopesList[$k]['money']        = round($to_price + $l['purchasing_expense'] + $l['expense'] - $l['give_money'] - $l['purchasing_discount'], 2);
            $envelopesList[$k]['gong']         = $l['gong'];
            $envelopesList[$k]['created_time'] = !empty($l['created_time']) ? date('Y-m-d H:i:s', $l['created_time']) : '';
            $envelopesList[$k]['type']         = $l['type'];
            $envelopesList[$k]['envelopes_id'] = $l['envelopes_id'];
            
            
        }
        
        $Common             = \app\api\model\Common::order_for_payment($orderId);
        $content            = '';
        $toExamine          = 0;
        $toExaminePaymentId = 0;
        
        if ($Common[6] != 0) {
            $toExamine = $Common[6];
        }
        if ($Common[7] != 0) {
            $toExaminePaymentId = $Common[7];
        }
        $list['toExamine']          = $toExamine;
        $list['toExaminePaymentId'] = $toExaminePaymentId;
        //质保
        if ($list['new_warranty_card'] == 1) {
            $Warranty['count'] = db('warranty_collection')->where('order_id', $orderId)->where('type', 1)->where('pro_types', 0)->count();
            $Warranty['title'] = "完工完款后领取";
        } else {
            if (!empty($Warranty)) {
                $Warranty['count'] = count($Warranty['data']);
                $Warranty['title'] = "完工完款后自动生效";
                unset($Warranty['data']);
                
            }
        }
        
        
        $list['Warranty'] = $Warranty;
        $b                = array_column($envelopesList, 'created_time');
        array_multisort($b, SORT_DESC, $envelopesList);
        $list['quotationHistory'] = $envelopesList;
        $list['order_id']         = $orderId;
        return $list;
    }
    public function orderConstructionAdministration($orderId) {
        $list = $this->field('st.sta_time as startupTime,st.up_time,st.xiu_id as mastId,sign.addtime,order_info.gong,order.start_time,order.tui_jian,order.finish_time,order_aggregate.main_price,order_aggregate.agent_price,order_aggregate.material_price,order_aggregate.material_agent_price,order.attributions,order_aggregate.reimbursement_price,order_aggregate.reimbursement_agent_price,order_aggregate.master_price,order_aggregate.master_half_price,order_setting.order_fee,order_setting.stop_agent_reimbursement as isNewRequisition,order_info.assignor,order.cleared_time,order.settlement_time,order_times.change_work_time,order_times.signing_time as signingTime')->join('sign', 'order.order_id=sign.order_id', 'left')->join('order_setting', 'order.order_id=order_setting.order_id', 'left')->join('order_times', 'order.order_id=order_times.order_id', 'left')->join('order_aggregate', 'order.order_id=order_aggregate.order_id', 'left')->join('order_info', 'order.order_id=order_info.order_id', 'left')->join('startup st', 'order.startup_id=st.startup_id', 'left')->where('order.order_id', $orderId)->find();
        //施工计划
        $signing_time = 0;
        if (!empty($list['addtime'])) {
            //预计开工时间
            $signing_time = !empty($list['addtime']) ? date('Y-m-d H:i:s', $list['addtime']) : '';
            
        } elseif (!empty($list['startupTime']) && empty($list['addtime'])) {
            //预计开工时间
            $signing_time = !empty($list['startupTime']) ? date('Y-m-d H:i:s', $list['startupTime']) : '';
        }
        $list['scheduledDate'] = "--";
        if (!empty($list['start_time']) && !empty($list['up_time'])) {
            $list['scheduledDate'] = $list['gong'] . "天(" . date('Y-m-d', $list['start_time']) . "至" . date('Y-m-d', $list['up_time']) . ")";
        }
        
        $start_time                     = !empty($list['start_time']) ? date('Y-m-d H:i:s', $list['start_time']) : '--';
        $finish_time                    = !empty($list['finish_time']) ? date('Y-m-d H:i:s', $list['finish_time']) : '--';
        $list['actualCommencementTime'] = $start_time . "至" . $finish_time;
        //延期提示
        $content = '';
        if (!empty($list['start_time'])) {
            if ($list['start_time'] + $list['gong'] * 24 * 60 * 60 > strtotime($signing_time) + $list['gong'] * 24 * 60 * 60) {
                $content = '超出预计工期';
            }
            $finish_time = date('Y-m-d H:i:s', $list['start_time'] + $list['gong'] * 24 * 60 * 60);
        } else {
            
            if (strtotime($signing_time) < time() && !empty($signing_time)) {
                $content = '开工已延期';
            }
        }
        
        $list['delay'] = $content;
        //派单师傅
        $relation       = \db('app_user_order_capital_relation')->join('app_user', 'app_user.id=app_user_order_capital_relation.user_id', 'left')->where('app_user_order_capital_relation.order_id', $orderId)->field('app_user.username,app_user.origin')->group('app_user_order_capital_relation.capital_id')->whereNull('app_user_order_capital_relation.deleted_at')->select();
        $app_user_order = \db('app_user_order')->join('app_user', 'app_user.id=app_user_order.user_id', 'left')->where('app_user_order.order_id', $orderId)->field('app_user.username,app_user.origin')->whereNull('app_user_order.deleted_at')->select();
        $cooperation    = [];
        foreach ($app_user_order as $item) {
            if ($item['origin'] == 2) {
                $cooperation[] = $item;
            }
        }
        $list['sectMaster'] = !empty($app_user_order) ? implode(',', array_unique(array_column($app_user_order, 'username'))) : '';
        //清单数量
        $capital = db('capital')->field('sum(if(agency=1,1,0)) as agency,sum(if(agency=0,1,0)) as man')->where('ordesr_id', $orderId)->where('types', 1)->where('enable', 1)->select();
        
        //有没有协作
        $list['cooperation'] = empty($cooperation) ? 0 : 1;
        //为派单师傅
        $dispatchFor = $capital[0]['man'] - count($relation);
        if ($dispatchFor < 0) {
            $dispatchFor = 0;
        }
        $list['dispatchFor'] = $dispatchFor;
        //巡检验收
        $list['listNumber']     = $capital[0]['man'] + $capital[0]['agency'];


        if ($list['change_work_time'] > 1748534400) {
            $auxiliary_project_list = \db('auxiliary_delivery_schedule')->join('capital', 'capital.capital_id=auxiliary_delivery_schedule.capital_id', 'left')->where('auxiliary_delivery_schedule.order_id', $orderId)->where('capital.types', 1)->where('capital.enable', 1)->where('auxiliary_delivery_schedule.work_process_accept_std_type', 3)->column('auxiliary_delivery_schedule.id');

            $list['manifestNode'] = count($auxiliary_project_list);
        } else {
            $auxiliary_project_list = \db('auxiliary_delivery_schedule')->join('auxiliary_project_list', 'auxiliary_delivery_schedule.auxiliary_project_list_id=auxiliary_project_list.id', 'left')->join('capital', 'capital.capital_id=auxiliary_project_list.capital_id', 'left')->where('auxiliary_project_list.order_id', $orderId)->where('capital.types', 1)->whereNull('auxiliary_project_list.delete_time')->where('capital.enable', 1)->column('auxiliary_delivery_schedule.id');

            $list['manifestNode'] = count($auxiliary_project_list);
        }
         $list['tobeReviewed'] = !empty($auxiliary_project_list) ? \db('auxiliary_delivery_node')->whereIn('auxiliary_delivery_schedul_id', $auxiliary_project_list)->where('state', 0)->count() : 0;
        //主材待验收
        $list['acceptance'] = \db('capital')->whereIn('ordesr_id', $orderId)->where('types', 1)->where('enable', 1)->where('agency', 1)->where('acceptance', 0)->count() . "项主材待验收,查看记录>";
        //$response['data']
        $agency_task = \db('agency_task')->where('status', '<>', 2)->whereIn('order_id', $orderId)->field('agency_staff_id,agency_id')->where('delete_time', 0)->select();
        //不台格待处理
        $list['previousAcceptance'] = \db('app_user_previous_acceptance')->whereIn('order_id', $orderId)->where('standard', '<>',1)->where('state', 3)->count();
        $list['agencyOrder'] = '';
        foreach ($agency_task as $v) {
            if ($v['agency_staff_id'] == 0 && $v['agency_id'] == 0) {
                $list['agencyOrder'] = '未选择供应商，请尽快选择';
            }
            
        }
       
        //查询报价金额
        $TotalProfit=$this->SingleSettlement($orderId);
        //直售金额
        $agenDirectSalesAndFixedDeliverOriginallyMoney=array_sum(array_column($TotalProfit['agenDirectSalesAndFixedDeliver'], 'originally_to_price'));
        $manDirectSalesAndFixedDeliverMOriginallyoney=array_sum(array_column($TotalProfit['manDirectSalesAndFixedDeliver'], 'originally_to_price'));
        //直售提成
        $agenDirectSalesAndFixedDeliverMoney=array_sum(array_column($TotalProfit['agenDirectSalesAndFixedDeliver'], 'to_price'));
        $manDirectSalesAndFixedDeliverMoney=array_sum(array_column($TotalProfit['manDirectSalesAndFixedDeliver'], 'to_price'));
         //直售固定成本
        $agenDirectSalesAndFixedDeliverFixedCostMoney=array_sum(array_column($TotalProfit['agenDirectSalesAndFixedDeliver'], 'fixed_cost'));
        $manDirectSalesAndFixedDeliverFixedCostMoney=array_sum(array_column($TotalProfit['manDirectSalesAndFixedDeliver'], 'fixed_cost'));
        //代购材料
        $sysConfig       = db('sys_config', config('database.zong'))->where('keyss', 'agent_material_code')->where('statusss', 1)->value('valuess');
        $reimbursement=\db('reimbursement')->where('status',1)->where('order_id', $orderId)->field('sum(if(classification !=4,money,0)) as reimbursement_price,sum(if(classification =4,money,0)) as reimbursement_agent_price')->select();
        
       
       
        //订单费
        // if ($list['manActual'] != 0) {
        //     $list['manActual'] =  $list['manActual'] -$list['order_fee'];
        // }
       
        //  //订单费
        // if ($list['agentActual'] != 0) {
        //     $list['agentActual'] =  $list['agentActual'] -$list['order_fee'];
        // }
        $aggregate=[];
        //主合同公司提成
        if ($list['main_price'] != 0) {
           
            $labor_cost_config = db('labor_cost_config', config('database.zong'))->where('city_id', config('cityId'))->find();
            //措施费
            $fixed_labor_cost_ratio = bcmul($list['main_price'], ($labor_cost_config['fixed_labor_cost_ratio'] / 100), 2);
            $fixed_labor_cost_ratio=0;
            //主合同材料领用
            $material_price = db('material_usage')->where(['status' => 1, 'order_id' => $orderId])->whereNotIn('invclasscode', $sysConfig)->sum('total_price');
            $master_price = \db('app_user_order_capital')->whereNull('deleted_at')->where('order_id', $orderId)->sum('personal_price');
            //报销费用
            $reimbursement_price = empty($reimbursement[0]['reimbursement_price']) ? 0 : $reimbursement[0]['reimbursement_price'];
            //主合同预计利润
            $manActual = sprintf("%.2f", ($TotalProfit['MainMaterialMoney'] - $material_price - $reimbursement_price - $master_price - $list['master_half_price'] - $fixed_labor_cost_ratio));
            $_main_discount_amount = 0;
            if ($list['cleared_time'] > 1732982400 || empty($list['cleared_time'])) {
                $_main_discount_amount = db('approval_record', config('database.zong'))->where("order_id", $orderId)->where("type", 2)->where('status', 1)->where('created_time', '>', $list['change_work_time'])->sum('change_value');
            }
            //提成比例
            $biLi = 0;
            //主合同利润率
            // $list['manActualProfit'] = (sprintf("%.4f", $list['manActual'] / ($list['main_price']+$_main_discount_amount)) * 100) . "%";

            //主合同公司提成
            $manCompanyCommission = round(($TotalProfit['MainMaterialMoney'] + $_main_discount_amount) * 0.33, 2);
            $biLi = 0.33;
            //KA+线下 (主合同35%，代购合同26%)：B端渠道
            if ($list['change_work_time'] > 1738339200 && ($list['attributions'] == 2 || $list['attributions'] == 3)) {
                $manCompanyCommission = round(($TotalProfit['MainMaterialMoney'] + $_main_discount_amount) * 0.35, 2);
                $biLi = 0.35;
            }
            //线上（主合同33%）：C端渠道
            if ($list['change_work_time'] > 1738339200 && $list['attributions'] == 1) {
                $manCompanyCommission = round(($TotalProfit['MainMaterialMoney'] + $_main_discount_amount) * 0.33, 2);
                $biLi = 0.33;
            }
            //复转 (主合同28%)：自主复转
            if ($list['change_work_time'] > 1738339200 && $list['attributions'] == 4) {
                $manCompanyCommission = round(($TotalProfit['MainMaterialMoney'] + $_main_discount_amount) * 0.28, 2);
                $biLi = 0.28;
            }
            // 要增加一个结算计算逻辑，从2025年2月1日起，广州的美化业务，既集团是“广州链家”的，order.attributions==3的订单，主合同结算提点为30%
            if ($list['change_work_time'] > 1738339200 && $list['attributions'] == 3 && config('cityId') == 200) {
                $personal = db('personal')->where("personal_id", $list['tui_jian'])->where("num", 2000000000148)->count();
                if ($personal > 0) {
                    $manCompanyCommission = round(($TotalProfit['MainMaterialMoney'] + $_main_discount_amount) * 0.3, 2);
                    $biLi = 0.3;
                }
            }
               // 要增加一个结算计算逻辑，从2025年2月1日起，成都的美化业务，既集团是“成都链家”的，order.attributions==3的订单，主合同结算提点为30%
            if ($list['change_work_time'] > 1738339200 && $list['attributions'] == 3 && config('cityId') == 241) {
                $personal = db('personal')->where("personal_id", $list['tui_jian'])->where("num", 2410000004463)->count();
                if ($personal > 0) {
                    $manCompanyCommission = round(($TotalProfit['MainMaterialMoney'] + $_main_discount_amount) * 0.3, 2);
                    $biLi = 0.3;
                }
            }
            $manCompanyCommissionList=null;
             $prompt="";
            
            if ($TotalProfit['manConvention'] >0) {
               
                //常规计提
                $manConvention = round(array_sum($TotalProfit['manConvention']) * $biLi, 2);
                // 公司固定计提
                $manFixedCompany = round(array_sum(array_column($TotalProfit['manFixedCompany'], 'to_price')), 2);
                $manCompanyCommission = $manConvention + $manFixedCompany;
                $manCompanyCommissionList = [
                    'title' => "公司总提成:" . $manCompanyCommission . "元;包含如下",
                    'describe' => "",
                    'date' => [
                        ['title' => "常规合同制计提（" . ($biLi * 100) . "%)", 'content' => ['总计：' . $manConvention . "元"]],
                        ['title' => "公司固定计提清单", 'content' => !empty($TotalProfit['manFixedCompany']) ? array_column($TotalProfit['manFixedCompany'], 'title') : ["无固定计提清单"]]
                    ]

                ];
                $prompt="主合同金额已扣除直售清单金额(".$manDirectSalesAndFixedDeliverMOriginallyoney.")";
                $TotalProfit['MainMaterialMoney']=bcsub($TotalProfit['MainMaterialMoney'],$manDirectSalesAndFixedDeliverMOriginallyoney,2);
                $manActual=bcsub($manActual,$manDirectSalesAndFixedDeliverMOriginallyoney,2);
  
            }
           
             //主合同金额
            $mantAmountTo =bcadd(bcsub ($manActual,$manCompanyCommission,2),$manDirectSalesAndFixedDeliverFixedCostMoney,2);
            $man = [
                'title' => "主合同",
                'amount' => $mantAmountTo."元",
                'list' => [
                    [
                        "title" => "主合同金额",
                        "prompt" =>  $prompt,
                        'amount' => $TotalProfit['MainMaterialMoney'],
                        'isBall' => 0
                    ],
                    [
                        "title" => "公司提成",
                        "prompt" => "",
                        'amount' =>  "-".$manCompanyCommission,
                        'isBall' => empty($manCompanyCommissionList)?0:1,
                        'data' => $manCompanyCommissionList
                    ],
                      [
                        "title" => "对冲人工费用中的直售成本",
                        "prompt" => "",
                        'amount' => "+".$manDirectSalesAndFixedDeliverFixedCostMoney,
                        'isBall' => 0
                      ],
                    [
                        "title" => "已报销费用",
                        "prompt" => "",
                        'amount' => "-".$reimbursement_price,
                        'isBall' => 0
                    ],
                    [
                        "title" => "已支出材料费用",
                        "prompt" => "",
                        'amount' => "-".$material_price,
                        'isBall' => 0
                    ],
                    [
                        "title" => "已支出人工费用",
                        "prompt" => "",
                        'amount' => "-".$master_price,
                        'isBall' => 0
                    ],
                    [
                        "title" => "超限优惠金额",
                        "prompt" => "",
                        'amount' => "-".$_main_discount_amount,
                        'isBall' => 0


                    ]
                ]
            ];
            array_push($aggregate, $man);
        }

        //代购合同公司提成
        if ($list['agent_price'] != 0) {
          $agenbiLi = 0;
        //代购人工费
        $reimbursement_agent_price=empty($reimbursement[0]['reimbursement_agent_price'])?0:$reimbursement[0]['reimbursement_agent_price'];
        //代购合同材料领用
        $material_agent_price = db('material_usage')->where(['status' => 1, 'order_id' => $orderId])->where('adopt', '>', '1648742400')->whereIn('invclasscode', $sysConfig)->sum('total_price');
         //代购合同预计利润
         $agentActual = sprintf("%.2f", ($TotalProfit['agencyMoney'] - $material_agent_price - $reimbursement_agent_price));
        //朝鲜优惠金额
            $_agent_discount_amount=0;
            if($list['settlement_time']>1732982400 || empty($list['settlement_time'])){
                $_agent_discount_amount=db('approval_record',config('database.zong'))->where("order_id",$orderId)->where("type", 3)->where('status', 1)->where('created_time','>',$list['change_work_time'])->sum('change_value');
            }
          
            //代购合同利润率
            // $agentActualProfit = (sprintf("%.4f", ($list['agentActual'] / ($list['agent_price']+$_agent_discount_amount))) * 100) . "%";
            
            
            //代购合同公司提成
            $agentCompanyCommission = round( ($TotalProfit['agencyMoney']+$_agent_discount_amount) * 0.23,2);
              $agenbiLi=0.23;
            if($list['attributions']==2){
                $agentCompanyCommission = round(($TotalProfit['agencyMoney']+$_agent_discount_amount) * 0.26, 2);
                $agenbiLi=0.26;
            }
             //KA+线下代购合同26%：B端渠道
            if($list['change_work_time']>1738339200 && ($list['attributions']==2 || $list['attributions']==3)){
                $agentCompanyCommission = round(($TotalProfit['agencyMoney']+$_agent_discount_amount) * 0.26,2);
                 $agenbiLi=0.26;
            }
            //线上代购合同23%：C端渠道  复转 (主合同28%，代购保持 23%)：自主复转
            if($list['change_work_time']>1738339200 && ($list['attributions']==1 || $list['attributions']==4)){
                $agentCompanyCommission = round(($TotalProfit['agencyMoney']+$_agent_discount_amount) * 0.23,2);
                 $agenbiLi=0.23;
            }
           
            $agentCompanyCommissionList=null;
            $prompt='';
            if($TotalProfit['agenConvention']>0){
                //常规计提
                $agenConvention=round(array_sum($TotalProfit['agenConvention'])* $agenbiLi,2);
                // 公司固定计提
                $agenFixedCompany=round(array_sum(array_column($TotalProfit['agenFixedCompany'],'to_price')),2);
                $agentCompanyCommission=$agenConvention+$agenFixedCompany;
                $agentCompanyCommissionList=[
                    'title'=>"公司总提成:".$agentCompanyCommission."元;包含如下",
                    'describe'=>"",
                    'date'=>[
                        ['title'=>"常规合同制计提（".( $agenbiLi*100)."%)",'content'=>['总计：'.$agenConvention."元"]],
                        ['title'=>"公司固定计提清单",'content'=>!empty($TotalProfit['agenFixedCompany'])?array_column($TotalProfit['agenFixedCompany'],'title'):["无公司固定计提清单"]]
                    ]
                    
                ];
                 $prompt="代购合同金额已扣除直售清单金额(".$agenDirectSalesAndFixedDeliverOriginallyMoney.")";
                 $TotalProfit['agencyMoney']=bcsub($TotalProfit['agencyMoney'],$agenDirectSalesAndFixedDeliverOriginallyMoney,2);
                $agentActual=bcsub($agentActual,$agenDirectSalesAndFixedDeliverOriginallyMoney,2);
            }
            //代购合同金额
            $agentAmountTo =bcadd(bcsub ($agentActual,$agentCompanyCommission,2),$agenDirectSalesAndFixedDeliverFixedCostMoney,2);
            $agent=[
                'title' => "代购合同",
                'amount' => $agentAmountTo."元",
                'list' => [
                    [
                        "title" => "代购合同金额",
                        "prompt" => $prompt,
                        'amount' => $TotalProfit['agencyMoney'],
                        'isBall' => 0
                    ],
                    [
                        "title" => "公司提成",
                        "prompt" => "",
                        'amount' =>"-".$agentCompanyCommission,
                        'isBall' => empty($agentCompanyCommissionList)?0:1,
                        'data'=>$agentCompanyCommissionList
                    ],
                    [
                        "title" => "已请款费用",
                        "prompt" => "",
                        'amount' => "-".$reimbursement_agent_price,
                        'isBall' => 0
                    ],
                     [
                        "title" => "对冲人工费用中的直售成本",
                        "prompt" => "",
                        'amount' =>"+". $agenDirectSalesAndFixedDeliverFixedCostMoney,
                        'isBall' => 0
                      ],
                    [
                        "title" => "已支出材料费用",
                        "prompt" => "",
                        'amount' =>"-". $material_agent_price,
                        'isBall' => 0
                    ],
                    [
                        "title" => "超限优惠金额",
                        "prompt" => "",
                        'amount' => "-".$_agent_discount_amount,
                        'isBall' => 0
                    ]

                ]
                    ];
                    array_push($aggregate,$agent);
        }
       
       
        if(bcadd($agenDirectSalesAndFixedDeliverMoney,$manDirectSalesAndFixedDeliverMoney,2)>0){
           $directSalesAndFixedDeliverMone= bcadd($agenDirectSalesAndFixedDeliverMoney,$manDirectSalesAndFixedDeliverMoney,2);
           $directSalesAmount=bcadd($agenDirectSalesAndFixedDeliverOriginallyMoney,$manDirectSalesAndFixedDeliverMOriginallyoney,2);
           $directSalesFixedCostAmount=bcadd($agenDirectSalesAndFixedDeliverFixedCostMoney,$manDirectSalesAndFixedDeliverFixedCostMoney,2);
            $mandirectSalesList = [
                'title' => "直售固提产品如下",
                'describe' => "直售产品计算业绩，提成按照售价固定比例给销售提成，订单总提成不再计算。直售产品不计入超额业绩奖励。",
                'date' => [
                    [
                        'title' => "主合同",
                         'content' => !empty($TotalProfit['manDirectSalesAndFixedDeliver']) ? array_column($TotalProfit['manDirectSalesAndFixedDeliver'], 'title') : null
                    ],
                    [
                        'title' => "代购",
                         'content' => !empty($TotalProfit['agenDirectSalesAndFixedDeliver']) ? array_column($TotalProfit['agenDirectSalesAndFixedDeliver'], 'title') : null
                    ]
                    
                ]

            ];
             
            $mandirectSales=[
                'title' => "直售产品清单",
                'amount' => $directSalesAndFixedDeliverMone,
                'list' => [
                    [
                        "title" => "直售金额",
                        "prompt" => "",
                        'amount' => $directSalesAmount,
                        'isBall' => 0
                    ],
                    [
                        "title" => "店长直售固定提成",
                        "prompt" => "",
                        'amount' => $directSalesAndFixedDeliverMone,
                        'isBall' => empty($mandirectSalesList)?0:1,
                        'data'=>$mandirectSalesList
                    ],
                    [
                        "title" => "直售固定成本",
                        "prompt" => "",
                        'amount' => $directSalesFixedCostAmount,
                        'isBall' => 0
                    ],
                     [
                        "title" => "公司提成",
                        "prompt" => "",
                        'amount' => bcsub(bcsub($directSalesAmount,$directSalesAndFixedDeliverMone,2),$directSalesFixedCostAmount,2),
                        'isBall' => 0
                        ]

                ]
                    ];
   
            array_push($aggregate,$mandirectSales);
        }
 
        //判断
        $list['profitDisplay'] = 2;
         if ((empty($list['cleared_time'])  && !empty($list['settlement_time'])  && $list['settlement_time'] <1725120000) ||  (!empty($list['cleared_time'])  && empty($list['settlement_time'])  && $list['cleared_time'] <1725120000) || (!empty($list['cleared_time']) && !empty($list['settlement_time']) && ($list['settlement_time'] <1725120000 || $list['cleared_time'] <1725120000))) {
            $list['profitDisplay'] = 1;
        }
        //实时预计提成
        $list['commissionAmount']=bcadd(bcadd (($mantAmountTo??0),($agentAmountTo??0),2),($directSalesAndFixedDeliverMone??0),2);
        $list['commissionAmountList']=$aggregate;
      
        $reimbursement     = db('reimbursement')->field('sum(if(classification=4,1,0)) as agentRequestFunds,sum(if(classification !=4,1,0)) as mainRequestFunds')->where('order_id', $orderId)->whereIn('status' ,[0,3])->select();
        $mainRequestFunds  = empty($reimbursement[0]['mainRequestFunds']) ? 0 : $reimbursement[0]['mainRequestFunds'];
        $agentRequestFunds = empty($reimbursement[0]['agentRequestFunds']) ? 0 : $reimbursement[0]['agentRequestFunds'];
        //费用报销
        $list['reimbursement'] = $mainRequestFunds . "条费用报销，审核中，查看记录>";
        //主材请款
        $list['agentRequestFunds'] = $agentRequestFunds . "项主材请款,审核中,查看记录>";
         $secondment=\db('secondment')->join('routine_usage','routine_usage.id=secondment.debi_id','left')->join('order','order.order_id=routine_usage.order_id','left')->join('store','store.store_id=secondment.lender_store_id','left')->where(['secondment.category' => 2,'secondment.status' => 3,'routine_usage.order_id'=>$orderId])->count();
         $material_usageCount=db('material_usage')->where(['order_id' => $orderId, 'status' => 0])->count();
        $list['material_usage']    =($material_usageCount+$secondment)  . "条材料领用，审核中，查看记录>";
        $list['order_id']          = $orderId;
        $workCapitalTypeListId     = \db('work_capital_procedure')->join('work_capital_type', 'work_capital_procedure.work_capital_type_id=work_capital_type.id', 'left')->field('GROUP_CONCAT(work_capital_type.type_work,"-",work_capital_procedure.working_procedure) as typeWork')->group('work_capital_procedure.id')->where('work_capital_procedure.working_start', '<', time())->where('work_capital_procedure.working_end', '>', time())->where('work_capital_procedure.deleted_at', 0)->where(['work_capital_type.order_id' => $orderId])->select();
        $workCapitalCount          = \db('work_capital_procedure')->join('work_capital_type', 'work_capital_procedure.work_capital_type_id=work_capital_type.id', 'left')->where('work_capital_procedure.working_start', '<>', 0)->where('work_capital_procedure.working_end', '<>', 0)->where('work_capital_procedure.deleted_at', 0)->where(['work_capital_type.order_id' => $orderId])->select();
        $typeWork                  = "";
        if (count($workCapitalCount) == 0) {
            $typeWork = "未设置工序时间，请及时设置";
        }
        // $work_check   = Db::connect(config('database.db2'))->table('work_check')->where(['order_id' => $orderId])->field('sum(if(state=0 or state=3,1,0)) as incomplete,sum(if(state !=0 or state !=3,1,0)) as Finished')->where('delete_time', 0)->group('order_id')->select();
        // $list_process = Db::connect(config('database.zong'))->table('sys_config')->where('keyss', 'list_process')->find();
        // $list_process = json_decode($list_process['valuess'], true);
        if (!empty($workCapitalTypeListId)) {
            $typeWork = array_unique(array_column($workCapitalTypeListId, 'typeWork'));
            $typeWork = implode("、’", $typeWork);
        }
        $order_completion   = Db::connect(config('database.zong'))->table('order_completion')->where(['order_id' => $orderId])->select();
        // if (!empty($work_check) && $work_check[0]['Finished'] == count($list_process)) {
        //     $list['completionTips'] = "验收通过";
        // }
        $list['completionTips'] = "用户未验收";
        if(in_array(2,array_column($order_completion,'inspection_type'))){
            $list['completionTips'] = "用户验收不通过";
        }
        if(in_array(3,array_column($order_completion,'inspection_type'))){
            $list['completionTips'] = "用户验收通过";
        }
        $list['typeWork'] = $typeWork;
        unset($list['startupTime'], $list['start_time'], $list['finish_time'], $list['gong'], $list['addtime']);
        return $list;
    }
    
    /*
     * 我的奖励
     */
    public function RewardDetails($orderId) {
        $list = db('order', config('database.zong'))->field('order.order_id,if(ifnull(order.start_time,0)=0,"未开工",FROM_UNIXTIME(start_time,"%Y-%m-%d %H:%i:%s")) as actualStartTime,if(ifnull(order.finish_time,0)=0,"未完工",FROM_UNIXTIME(finish_time,"%Y-%m-%d %H:%i:%s")) as finishTime,order.state,FROM_UNIXTIME(order.created_time,"%Y-%m-%d %H:%i:%s")as createdTime,order_aggregate.total_price as totalPrice,order_aggregate.main_increment_price,order_aggregate.agent_increment_price,if(ifnull(order_times.signing_time,0)=0,"未签约",FROM_UNIXTIME(signing_time,"%Y-%m-%d %H:%i:%s")) as contractConTime,if(ifnull(order_times.envelopes_time,0)=0,"未报价",FROM_UNIXTIME(envelopes_time,"%Y-%m-%d %H:%i:%s")) as envelopesTime,if(ifnull(order_times.late_clock_time,0)=0,"未打卡",FROM_UNIXTIME(late_clock_time,"%Y-%m-%d %H:%i:%s")) as lateClockTime,ifnull(user.username,"未指派") as username,ifnull(user.mobile,"未指派") as mobile,if(order_info.store_name="","未指派",order_info.store_name) as storeName')->join('order_info', 'order.order_id=order_info.order_id', 'left')->join('user', 'order.assignor=user.user_id', 'left')->join('order_aggregate', 'order.order_id=order_aggregate.order_id', 'left')->join('order_times', 'order.order_id=order_times.order_id', 'left')->where('order.order_id', $orderId)->find();
        //减项金额
        $list['subtract'] = 0;
        if (!empty($list['contractConTime'])) {
            $list['subtract'] = \db('capital', config('database.zong'))->whereIn('ordesr_id', $orderId)->where('types', 2)->where('untime', '>', $list['contractConTime'])->sum('to_price');
        }
        $myOrderAward = \db('my_order_award', config('database.zong'))->where('order_id', $orderId)->field('if(my_order_award.state=1,my_order_award.profit,0) as adopt,if(my_order_award.state=2,my_order_award.profit,0) as reject')->where('type', 1)->select();
        //审核通过奖励
        $list['adopt'] = empty($myOrderAward) ? 0 : array_sum(array_column($myOrderAward, 'adopt'));
        //审核驳回奖励
        $list['reject'] = empty($myOrderAward) ? 0 : array_sum(array_column($myOrderAward, 'reject'));
        //增项金额
        $list['additions'] = bcadd($list['main_increment_price'], $list['agent_increment_price'], 2);
        
        $list['state'] = self::type($list['state']);
        
        unset($list['main_increment_price'], $list['agent_increment_price']);
        
        return [['title' => '录入时间', 'content' => $list['createdTime']], ['title' => '订单状态', 'content' => $list['state']], ['title' => '审核通过奖励', 'content' => $list['adopt']], ['title' => '审核驳回奖励', 'content' => $list['reject']], ['title' => '订单所属店铺', 'content' => $list['storeName']], ['title' => '店长姓名', 'content' => $list['username']], ['title' => '店长电话', 'content' => $list['mobile']], ['title' => '上门打卡时间', 'content' => $list['lateClockTime']], ['title' => '报价时间', 'content' => $list['envelopesTime']], ['title' => '签约时间', 'content' => $list['contractConTime']], ['title' => '增项金额', 'content' => $list['additions']], ['title' => '减项金额', 'content' => $list['subtract']], ['title' => '开工时间', 'content' => $list['actualStartTime']], ['title' => '完工时间', 'content' => $list['finishTime']]
        
        ];
    }
    
    
    public function reworkInfo($orderId,$userId) {
        $list = $this->field('order.order_id,rework_end.user_id as reworkEndUserId,FROM_UNIXTIME(order.created_time,"%Y-%m-%d %H:%i:%s")as createdTime,rework_end.type,order_info.assignor,user.username,order.state,order.hardbound,rework_end.attachment as img,rework_end.id,rework_end.after_sales_no as afterSalesNo,rework_end.description as causeAnalysis,rework_end.type,CASE
            WHEN rework_end.role=1  THEN  concat("店长（",user.username,"）")
             WHEN rework_end.role=2  THEN  "用户创建"
             WHEN rework_end.role=3 THEN  "客服创建" END as role,order.contacts,order.telephone,concat(order_info.pro_id_title,"-",order_info.pro_id1_title) as proIdTitle,concat(order_info.city,order_info.county,order.addres,order.street,order.building,order.unit,order.room) as addres,if(order.sex=1,"男","女") as sex,if(order.new_or_oldUser=1,"新用户","老用户") as newOrOldUser,FROM_UNIXTIME(rework_end.created_time,"%Y-%m-%d %H:%i:%s")as reworkCreatedTime,if(rework_end.confirmed_time !=0,FROM_UNIXTIME(rework_end.confirmed_time,"%Y-%m-%d %H:%i:%s"),0 )as confirmedTime,if(ifnull(rework_end.update_time,0) !=0 and rework_end.update_time>0,FROM_UNIXTIME(rework_end.update_time,"%Y-%m-%d %H:%i:%s"),0) as reworkAfterSalesCompletion,if(rework_end.completion_time !=0,FROM_UNIXTIME(rework_end.completion_time,"%Y-%m-%d %H:%i:%s"),0) as completionTime')->join('order_info', 'order.order_id=order_info.order_id', 'left')->join('rework_end', 'order.order_id=rework_end.order_id', 'left')->join('user', 'rework_end.user_id=user.user_id', 'left')->where('rework_end.id', $orderId)->find();
            if($list['reworkEndUserId'] != $userId){
                r_date(null, 300,"你无权查看该订单");
            }
//        $subordinate = $list['state'];
        $list['subordinate']       = 0;
        $list['stateTitle']        = '';
        if(!empty($list['reworkCreatedTime']) &&  empty($list['confirmedTime']) &&  empty($list['reworkAfterSalesCompletion'])&&  empty($list['completionTime'])){
            $list['subordinate']       = 12 ;
            $list['stateTitle']        ='售后沟通中';
        }elseif (!empty($list['reworkCreatedTime']) &&  !empty($list['confirmedTime']) &&  empty($list['reworkAfterSalesCompletion'])&&  empty($list['completionTime'])){
            $list['subordinate']       =  13 ;
            $list['stateTitle']        ='返工中';
        }elseif (!empty($list['reworkCreatedTime']) &&  !empty($list['confirmedTime']) &&  !empty($list['reworkAfterSalesCompletion'])&&  empty($list['completionTime'])){
            $list['subordinate']       = 14;
            $list['stateTitle']        ='待验收';
        }elseif (!empty($list['reworkCreatedTime']) &&  !empty($list['confirmedTime']) &&  !empty($list['reworkAfterSalesCompletion'])&& !empty($list['completionTime'])){
            $list['subordinate']       = 15;
            $list['stateTitle']        ='售后完成';
        }
        $list['img']               = !empty($list['img']) ? json_decode($list['img']) : null;
        $afterType              = [['id'=>1,'title'=>'施工质保售后','selected'=>0],[ 'id'=>2,'title'=>'主材质保售后','selected'=>0],['id'=>3,'title'=>'超质保期施工售后','selected'=>0],['id'=>4,'title'=>'超质保期主材售后','selected'=>0]];
        foreach ($afterType  as $k=>$l){
            if($l['id']==$list['type']){
                $afterType[$k]['selected']=1;
            }
        }
        $list['afterType'] =$afterType;
        $list['isNewOrder']        = !empty($list['receive_time']) ? 0 : 1;
        $list['constructionOrNot'] = db('rework_form')->where('end_id', $orderId)->count();
        if ($list['constructionOrNot'] == 0) {
            $timeAxis = [['title' => "售后沟通中", 'time' => empty($list['reworkCreatedTime']) ? $list['reworkCreatedTime'] : '', 'state' => 1], ['title' => "无需返工", 'time' => empty($list['confirmedTime']) ? " " : $list['confirmedTime'], 'state' => empty($list['confirmedTime']) ? 0 : 1], ['title' => "待验收", 'time' => empty($list['reworkAfterSalesCompletion']) ? " " : $list['reworkAfterSalesCompletion'], 'state' => empty($list['reworkAfterSalesCompletion']) ? 0 : 1],['title' => "售后完成", 'time' => empty($list['completionTime']) ? " " : $list['completionTime'], 'state' => empty($list['completionTime']) ? 0 : 1]];
        } else {
            $timeAxis = [['title' => "售后沟通中", 'time' => empty($list['reworkCreatedTime']) ? $list['reworkCreatedTime'] : '', 'state' => 1], ['title' => "返工中", 'time' => empty($list['confirmedTime']) ? " " : $list['confirmedTime'], 'state' => empty($list['confirmedTime']) ? 0 : 1], ['title' => "待验收", 'time' => empty($list['reworkAfterSalesCompletion']) ? " " : $list['reworkAfterSalesCompletion'], 'state' => empty($list['reworkAfterSalesCompletion']) ? 0 : 1],['title' => "售后完成", 'time' => empty($list['completionTime']) ? " " : $list['completionTime'], 'state' => empty($list['completionTime']) ? 0 : 1]];
        }
        $list['timeAxis'] = $timeAxis;
        
        $customers = db('customers', config('database.zong'))->field('if(if(customers_vip.vip_expire_time_start  <= unix_timestamp() and customers_vip.vip_expire_time_end>=unix_timestamp(),1,0)=1,1,0)as title')->join('customers_vip', 'customers_vip.customers_id=customers.customers_id', 'left')->where('customers.mobile', $list['telephone'])->find()['title'];
        
        $list['isVip']          = empty($customers) ? 0 : $customers;
        $title='质保售后';
        if($list['type']==1){
         $title='施工质保售后';
        }elseif ($list['type']==2){
            $title='主材质保售后';
        }elseif ($list['type']==3){
            $title='超质保期施工售后';
        }elseif ($list['type']==4){
            $title='超质保期主材售后';
        }
        $list['afterSalesType'] =$title;
        $master_id              = db('order_rework')->where(['order_id' => $list['order_id'], 'rework_end' => $orderId])->column('master_id');
        $username               = '';
        if (!empty($master_id)) {
            $username = db('app_user')->whereIn('id', $master_id)->column('username');
            $username = '派工师傅：' . implode(',', $username);
        }
        
        $list['constructionMaster']    = $username;
        $list['reworkMaterialUsage']   = db('rework_material_usage')->where(['end_id' => $orderId, 'status' => 0])->count() . '条材料领用申请,审核中';
        $list['reworkReimbursement']   = db('rework_reimbursement')->where(['end_id' => $orderId, 'status' => 0])->count() . '条费用报销,审核中';
        $list['whetherToCloseTheCase'] = empty($list['reworkAfterSalesCompletion']) ? "当前未结案查看" : "当前已结案查看";
        $list['state']                 = empty($list['reworkAfterSalesCompletion']) ? 1 : 3;
        unset($list['reworkAfterSalesCompletion']);
        return $list;
    }
    
    public function judge($item) {
        $order_id    = 0;
        $reworkId    = 0;
        $tips        = '';
        $remind      = '';
        $pending     = 0;
        $subordinate = 0;
        $stateTitle  = '';
        if ($item['state'] == 1 || $item['undetermined'] == 1) {
            $creationTime = !empty($item['dispatchTime']) ? "派单时间：" . date('Y-m-d H:i:s', $item['dispatchTime']) : '';
            $pending      = $item['tai'];
            $remind       = put_time($item['dispatchTime']);
            if ($item['undetermined'] == 1) {
                $pending = 2;
            }
            $subordinate = 1;
            $stateTitle  = '待接单';
        } elseif ((empty($item['envelopesTime']) && $item['state'] == 2) || (empty($item['envelopesTime']) && $item['state'] == 3) && $item['lateClockTime'] == 0 && $item['undetermined'] == 0) {
            //今日上门
            $planned      = $item['planned'] - time();
            $cTime        = time();
            $dDay         = intval(date("z", $item['planned'])) - intval(date("z", $cTime));
            $dYear        = intval(date("Y", $item['planned'])) - intval(date("Y", $cTime));
            $plannedTitle = '';
            if (!empty($item['planned'])) {
                if ($dYear == 0 && $dDay == 0) {
                    $plannedTitle = "今日上门";
                } else {
                    if ($dDay < 0) {
                        $plannedTitle = "超出" . abs($dDay) . "未上门";
                    } else {
                        $plannedTitle = $dDay . "天后上门";
                    }
                    
                }
            }
            
            //联系客户时间
            $th_time      = '';
            $DaysThrough  = intval(date("z", $cTime)) - intval(date("z", $item['lateThTime']));
            $DaysThrough1 = intval(date("Y", $cTime)) - intval(date("Y", $item['lateThTime']));
            if (!empty($item['lateThTime'])) {
                if ($dYear != 0 && $dDay != 0 && $DaysThrough != 0) {
                    $th_time = $DaysThrough . "天前联系客户";
                }
                
            }
            $creationTime = !empty($item['planned']) ? "预约上门时间：" . date('Y-m-d H:i:s', $item['planned']) : '';
            $tips         = $plannedTitle;
            $remind       = $th_time;
            $subordinate  = 2;
            $stateTitle   = '待上门';
        } elseif ((empty($item['envelopesTime']) && $item['state'] == 2) || (empty($item['envelopesTime']) && $item['state'] == 3) && $item['lateClockTime'] != 0) {
            
            $notQuoted = '';
            if (empty($item['envelopesFirstTime']) && !empty($item['firstClockTime'])) {
                $ttime = time() - $item['firstClockTime'];
                $d     = floor($ttime / 86400);                         //天
                if ($d > 3) {
                    $notQuoted = '超期' . $d . '天未报价';
                }
            }
            //联系客户时间
            $th_time     = '';
            $DaysThrough = round((time() - $item['lateThTime']) / 3600 / 24);
            if (!empty($item['lateThTime']) && $DaysThrough >= 1) {
                $th_time = $DaysThrough . "天前联系客户";
            }
            //打卡时间
            $creationTime = !empty($item['lateClockTime']) ? "上门时间：" . date('Y-m-d H:i:s', $item['lateClockTime']) : '';
            $tips         = $notQuoted;
            $remind       = $th_time;
            $subordinate  = 3;
            $stateTitle   = '待报价';
        } elseif ($item['state'] == 3 && $item['contractConTime'] == 0 && $item['envelopesTime'] != 0) {
            $ttime  = time() - $item['envelopesFirstTime'];
            $d      = floor($ttime / 86400);
            $quoted = '';//天
            if ($d != 0) {
                $quoted = '已报价' . $d . '天';
            }
            
            //联系客户时间
            $th_time     = '';
            $DaysThrough = round((time() - $item['lateThTime']) / 3600 / 24);
            if (!empty($item['lateThTime']) && $DaysThrough >= 1) {
                $th_time = $DaysThrough . "天前联系客户";
            }
            //打卡时间
            $creationTime = !empty($item['envelopesTime']) ? "报价时间：" . date('Y-m-d H:i:s', $item['envelopesTime']) : '';
            $tips         = $quoted;
            $remind       = $th_time;
            $subordinate  = 4;
            $stateTitle   = '待签约';
        } elseif ($item['state'] == 3 && $item['contractConTime'] != 0 && $item['envelopesTime'] != 0) {
            $creationTime = !empty($item['contractConTime']) ? "签约时间：" . date('Y-m-d H:i:s', $item['contractConTime']) : '';
            $ttime        = time() - $item['contractConTime'];
            $d            = floor($ttime / 86400);//天
            $quoted       = '';
            if ($d != 0) {
                $quoted = '已签约' . $d . '天';
            }
            
            $tips        = $quoted;
            $subordinate = 5;
            $stateTitle  = '已签约款不足';
        } elseif ($item['state'] == 4 && empty($item['actualStartTime'])) {
            
            $commencementScheduleIsNotSet = '';
            $expectedCommencement         = '';
            $signing_time                 = '';
            if (!empty($item['addtime'])) {
                $ttime                = time() - $item['addtime'];
                $d                    = floor($ttime / 86400);                         //天
                $expectedCommencement = abs($d) . '天后开工';
                //预计开工时间
                $signing_time = !empty($item['addtime']) ? "开工时间：" . date('Y-m-d H:i:s', $item['addtime']) : '';
                
            } elseif (!empty($item['startupTime']) && empty($item['addtime'])) {
                $ttime                = time() - $item['startupTime'];
                $d                    = floor($ttime / 86400);                         //天
                $expectedCommencement = abs($d) . '天后开工';
                //预计开工时间
                $signing_time = !empty($item['startupTime']) ? "开工时间：" . date('Y-m-d H:i:s', $item['startupTime']) : '';
            }
            if (empty($item['xiuId'])) {
                $commencementScheduleIsNotSet = '未设置开工安排';
            }
            $creationTime = $signing_time;
            
            $tips        = $expectedCommencement;
            $remind      = $commencementScheduleIsNotSet;
            $subordinate = 6;
            $stateTitle  = '待开工';
        } elseif ($item['state'] == 4 && !empty($item['actualStartTime'])) {
            $creationTime = !empty($item['actualStartTime']) ? "开工时间：" . date('Y-m-d H:i:s', $item['actualStartTime']) : '';
            $stateTitle  = '施工中';
            //                $tips         = '有巡检但验收';
            $subordinate = 7;
           
        } elseif ($item['state'] == 7 && ((empty($item['cleared_time']) && $item['main_price'] != 0 && $item['agent_price'] == 0) || (empty($item['cleared_time']) && empty($item['settlement_time']) && $item['main_price'] == 0 && $item['agent_price'] == 0) || (empty($item['settlement_time']) && $item['main_price'] == 0 && $item['agent_price'] != 0) || ((empty($item['cleared_time']) && $item['main_price'] != 0) or ($item['agent_price'] != 0 && empty($item['settlement_time']))) || ((empty($item['cleared_time']) && $item['main_price'] == 0 && ($item['material_price'] + $item['reimbursement_price']) != 0) or ($item['agent_price'] == 0 && empty($item['settlement_time']) && ($item['material_agent_price'] + $item['reimbursement_agent_price']) != 0)))) {
            $pendingPayment = '';
            $toBeSettled    = '';
            
            if ($item['total_price'] != $item['main_payment_price'] + $item['agent_payment_price']) {
                $pendingPayment = '待完款';
            }
            if (($item['main_price'] == 0 && $item['agent_price'] != 0 || $item['main_price'] != 0 && $item['agent_price'] != 0) && empty($item['acceptance_time'])) {
                $toBeSettled = '代购待验收';
            }
            $creationTime = !empty($item['finishTime']) ? "完工时间：" . date('Y-m-d H:i:s', $item['finishTime']) : '';
            $tips         = $pendingPayment;
            $remind       = $toBeSettled;
            $subordinate  = 8;
            $stateTitle   = '完工待结算';
        } elseif ($item['state'] == 7 && ((!empty($item['cleared_time']) && $item['main_price'] != 0 && $item['agent_price'] == 0) || (!empty($item['settlement_time']) && $item['main_price'] == 0 && $item['agent_price'] != 0) || (!empty($item['cleared_time']) && $item['main_price'] != 0 && $item['agent_price'] != 0 && !empty($item['settlement_time'])) || (!empty($item['cleared_time']) && !empty($item['settlement_time'])) || (!empty($item['cleared_time']) && $item['main_price'] == 0 && $item['agent_price'] == 0 && ($item['material_agent_price'] + $item['reimbursement_agent_price']) == 0) || (!empty($item['settlement_time']) && $item['main_price'] == 0 && $item['agent_price'] == 0 && ($item['material_price'] + $item['reimbursement_price']) == 0))) {
            $overTime = 0;
            if ($item['main_price'] != 0 && $item['agent_price'] != 0 && !empty($item['cleared_time']) && !empty($item['settlement_time'])) {
                $overTime = $item['cleared_time'];
            } elseif ($item['main_price'] != 0 && $item['agent_price'] == 0 && !empty($item['cleared_time'])) {
                $overTime = $item['cleared_time'];
            } elseif ($item['main_price'] == 0 && $item['agent_price'] != 0 && !empty($item['settlement_time'])) {
                $overTime = $item['settlement_time'];
            }
            $creationTime = !empty($overTime) ? "完结时间：" . date('Y-m-d H:i:s', $overTime) : '';
            $subordinate  = 9;
            $stateTitle   = '已完结';
        } elseif ($item['state'] == 8) {
            $creationTime = !empty($item['cancellationTime']) ? "取消时间：" . date('Y-m-d H:i:s', $item['cancellationTime']) : '';
            $subordinate  = 10;
            $stateTitle   = '已取消';
        } elseif ($item['state'] == 9) {
            //退单时间
            $creationTime = !empty($item['chargebackTime']) ? "退单时间：" . date('Y-m-d H:i:s', $item['chargebackTime']) : '';
            $subordinate  = 11;
            $stateTitle   = '已退单';
        }
        
        return ['subordinate' => $subordinate, 'stateTitle' => $stateTitle, 'creationTime' => isset($creationTime) ? $creationTime : 0, 'tips' => $tips, 'remind' => $remind, 'pending' => $pending, 'order_id' => $order_id, 'reworkId' => $reworkId];
    }
    
    
}